C++编写程序,计算s=1+(1+2)+(1+2+3)+…+(1+2+3+…+n)的值

2024-12-22 09:09:48
推荐回答(3个)
回答1:

#include

usingnamespacestd;

intmain()

{

intn;

staticintsum=1;

cout<<"请输入N:"<

cin>>n;

for(inti=1;i<=n;i++)

{

for(intj=1;j<=i;j++)

{

sum=sum+j;

}

}

cout<<"结果2为:"<

system("pause");

return0;

扩展资料

C语言计算1-1/3+1/5-……的前n项之和

#include

intmain(void){

inti,n;

doublef,s;

intflag=1,m=1;

printf("请输入分母的终值:");

scanf("%d",&n);

for(i=1,s=0;i<=n;i++)

{

f=flag*1.0/m;

s+=f;

flag=-flag;

m=m+2;

}

printf("1+1/3-1/5+...+1/n=%.2f\n",s);

system("pause");

return0;

}

回答2:

#include
using namespace std;
int main()
{
int s=0,sum=0,i,n;
cout<<"请输入n的值:";
cin>>n;
for(i=1;i<=n;i++)
{
sum+=i;
s+=sum;
}
cout< return 0;
}

回答3:

#include
void main()
{
int n;
printf("please input n:\n");
scanf("%d",&n);
int t = 0;
int sum = 0;
for(int i = 1; i <= n; i++)
{
t += i;
sum += t;
}
printf("sum = %d\n",sum);
}