1206 简单的累加

我比较喜欢解法二的for

解法1:while循环

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e3+10,inf = 0x3f3f3f3f;

int main()
{
    int n,ans = 0;
    cin >> n;
    ans = n;
    while(n--)
    {
        ans+=n;
    }
    cout << ans;
     return 0;
}

 

解法二:for循环

#include<bits/stdc++.h>
#define f(i,s,e) for(int i = s; i <= e; i++)
#define ll long long
using namespace std;
const int N = 1e3+10,inf = 0x3f3f3f3f;

int main()
{
    int n, sum = 0;
    cin >> n;
    for(int i = 1; i <= n; i++) //循环1到n
    {
        sum += i; //sum累加上循环变量i 
    } 
    cout << sum;
    return 0;
}

 

posted @ 2024-06-28 17:47  CRt0729  阅读(10)  评论(0编辑  收藏  举报