【问题标题】:A unexpected output with if condition带有 if 条件的意外输出
【发布时间】: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


【解决方案1】:

问题在于你的 if 语句:

if(i=n)

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

if(i==n)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案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 )
      

      【讨论】:

        猜你喜欢
        • 2016-11-01
        • 2011-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-07
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        相关资源
        最近更新 更多