2680: 练24.2 for循环求和
内存限制:64 MB
时间限制:1.000 S
评测方式:文本比较
命题人:
提交:115
解决:60
题目描述
利用for循环。计算输出$1+2+3+...+n$的和。
输入
输入$n$。对于100%的数据,$1≤n≤100$。
输出
如题述,之和。
样例输入 复制
10
样例输出 复制
55
提示
使用循环:
#include<bits/stdc++.h> using namespace std; int sum,n; int main(){ cin>>n; for(int i=1;i<=n;i++) sum+=i; cout<<sum; return 0; }
使用递归:
#include<bits/stdc++.h> using namespace std; int f(int x) { if (x==1) return 1; else return x+f(x-1); } int main(){ int n; cin>>n; cout<<f(n); return 0; }