1

对于我正在尝试编写的程序,我必须创建一个程序,要求用户输入一个数字并计算输入的所有数字的总和,直到用户输入 -1 以停止循环。但是,我无法打印 -1 或将其添加到总数中,但我正在努力解决这个问题。

#include <stdio.h>

int main ()
{
    int x, total;

    total = 0;
    x = 0;

    while (x <= -2 || x >= 0)
    {

        printf("Please enter a number: ");
        scanf("%d", &x);

        printf("You entered %d \n", x);

        totalSum = total + x;
        printf("total is %d \n", total);

    }

    printf("Have a nice day :) \n");
    printf("total is %d \n", total);

    return 0;
}

关于如何在不打印或添加到总数的情况下将循环停止在 -1 的任何建议?

4

2 回答 2

2

您可以在循环开始时检查输入是否等于-1,如果是则退出而不是计算:

while(1) {
    printf("Please enter a number: ");
    scanf("%d", &x);      

    if (-1 == x)
      break;

     ...
 }
于 2013-03-15T03:53:59.110 回答
0

对不起,当我看到一个完全由条件中断驱动的循环时,我会感到畏缩。while(1)怎么样的东西:

printf("Please enter a number: ");
while(scanf("%d", &x) == 1 && x != -1)
{
    // do work

    printf("Please enter a number: ");
}

One con to this method is the print is duplicated, but I believe that the pro of having the while conditional actually drive the loop more than makes up for it. An additional benefit is that scanf is also being checked here to make sure that it read in the next value correctly.

于 2013-03-15T11:59:09.873 回答