while 循环中的语句顺序错误

问题描述 投票:0回答:1

C: 中的代码片段

#include <stdio.h>

int main(void)
{
      int n, sum = 0;
      printf("This program lists terms with each term being sum of previous terms and itself\n");
      printf("Enter integers (0 to terminate): ");

      scanf("%d", &n);
      
      while (n != 0) {
          sum += n;
          scanf("%d", &n);
          printf("The sum is: %d\n", sum);
      }
}

如果我输入1,2,3;我的预期输出是 1、3 和 6。但是,除非我在

scanf
循环中将
printf
语句与
while
语句交换,否则 6 会被省略。这是为什么?

c while-loop
1个回答
0
投票

您的代码的问题是在您输入 3 之后,程序卡在 scanf 处,因此它正在等待输入。为了避免这种情况,首先打印总和,然后读取下一个输入。

#include <stdio.h>

int main(void)
{
      int n, sum = 0;
      printf("This program lists terms with each term being sum of previous terms and itself\n");
      printf("Enter integers (0 to terminate): ");

      scanf("%d", &n);
      
      while (n != 0) {
          sum += n;
          printf("The sum is: %d\n", sum);
          scanf("%d", &n);
      }
}
© www.soinside.com 2019 - 2024. All rights reserved.