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)
{
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
C程序,求数列1,-3!,5!,-7!,…,(-1)n-1(2n-1)!前n项的和。
C函数递归求1!+2!+3!+…+n!
求教C语言:求S=1!+2!+3!+…+n!,n从键盘输入??
C语言问题,请进来帮帮忙。求1+2+3+…+n>=500的最小n及和的值。
编写一C程序,求数列1,-3!,5!,-7!,…,(-1)n-1(2n-1)!前n项的和。
求1N、2N、3N ……..100N.2055N,这101个力的合力最小值
C++题目: 求N的阶乘 求N的阶乘(N<20)。N的阶乘=1*2*3*...*N,N值由键盘输入。
已知(a-3)^2+Ib+1I+c^2=0,求M-N的值。
证明C(0,n)^2+C(1,n)^2+……+C(n,n)^2=C(n,2n)
求解c语言编程题:求满足不等式1+1/2+1/3+...+1/n>15求最小的n值并输出