带有 if 条件的意外输出

A unexpected output with if condition

提问人:varun prasad 提问时间:12/9/2021 最后编辑:Vlad from Moscowvarun prasad 更新时间:12/9/2021 访问量:79

问:

我想使用一个程序来计算前 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 elseif

c if 语句 赋值运 比较运算符

评论

2赞 Gerhardh 12/9/2021
请在编译器中启用或打开警告。编译器应发出有关可疑使用条件的警告。=

答:

0赞 Dipesh Kumar 12/9/2021 #1

您在 if 语句中使用了 i=n 而不是 i==n。

1赞 racraman 12/9/2021 #2

问题出在你的if语句上:

if(i=n)

单个 = 是赋值;你想要的是与 == 的比较,所以:

if(i==n)
0赞 Vlad from Moscow 12/9/2021 #3

您在此 if 语句的表达式中使用赋值运算符而不是比较运算符===

      if(i=n)
      {
          printf("%d",i);
      }

你需要写

      if( i == n)
      {
          printf("%d",i);
      }

此外,最好使用 for 循环而不是 while 循环。

例如

for ( int i = 0; i < n;  )
{
    printf( ++i == n ? "%d" : "%d+", i );
    sum += i;
}

该变量仅在循环中使用。因此,它应该在使用它的范围内声明。i

始终尝试在使用变量的最小范围内声明变量。这将使您的程序更具可读性。

注意,根据 C 标准,没有参数的函数 main 应声明如下

int main( void )