【发布时间】:2022-01-14 06:35:58
【问题描述】:
我想写一个程序来计算前n个自然数之和
我尝试过的代码:
#include<stdio.h>
void main()
{
int sum=0,i=1,n;
printf("Enter the number upto where you want to print add : ");
scanf("%d",&n);
printf("\nSUM = ");
while(i<=n)
{
if(i<n)
{
printf("%d+",i);
}
if(i=n)
{
printf("%d",i);
}
sum=sum+i;
i++;
}
printf("\nThe sum of the first %d numbers is : %d",n,sum);
return 0;
}
而预期的输出是如果 n=5
Enter the number upto where you wnat to print add :
sum =1+2+3+4+5
The sum of the first %d numbers is : 5
但我得到的是
sum=1+5
and the value is 5
但是当我使用 if else 而不是两个 if 时,它的工作原理
【问题讨论】:
-
请在编译器中启用或打开您的警告。编译器应针对在某个条件下对
=的可疑使用发出警告。
标签: c if-statement assignment-operator comparison-operators