C++求1+2+3+…+n的值

来源:百度知道 编辑:UC知道 时间:2024/09/24 16:35:12
#include <iostream.h>
int sum(int n)
{
if (n<3
{
cout<<"error!"<<endl;
return 1;
}
else
{
return (n+sum(n-1));
}
}
void main()
{
int sum(int n);
int n;
cout<<"请输入n:"<<endl;
cin>>n;
cout<<"1+2+3+…+n="<<sum(n)<<endl;
}
我这个有点问题,输入一个数字,结果ERROR和计算结果都显示,哪里有问题?请帮我修改下

int sum(int n)
{
//我不知道你这为什么要这样写, 你用的递归法,但限定条件是n<3时终止递归并输出error;这个是你要让他输出的.而且结果肯定不对,
你这个是2 + 4 + 5 + ... + n; 而不是1 + 2 + 3 + ... + n
if (n<3) //这里条件为改为 n < 2 即从n一直加到 (n < 2) 即 1
{
cout<<"error!"<<endl; //这一行去掉
return 1;
}
else
{
return (n+sum(n-1));
}
}

#include <iostream>
using namespace std;
int sum(int n)
{
if (n<3 )
{
cout<<"error!"<<endl;
return -1;
}
else
{
return (n+sum(n-1));
}
}
int main()
{
int n;
cout<<"请输入n:"<<endl;
cin>>n;
cout<<"1+2+3+…+n="<<sum(n)<<endl;
return 0;
}

楼主,不要相信白痴老师。
用公式n(n+1)>>1来计算。用递归用迭代都是SB。
就算是教学需要也应该举更好的例子。中国教育的悲哀。

include <iostream.h>
int sum(int n)
{
if (n<3
{
co