Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 循环程序问题_C_While Loop_Sentinel - Fatal编程技术网

C 循环程序问题

C 循环程序问题,c,while-loop,sentinel,C,While Loop,Sentinel,对于我正在尝试编写的程序,我必须创建一个程序,要求用户输入一个数字,并计算输入的所有数字的总数,直到用户输入-1停止循环。然而,我无法打印-1或将其添加到总数中,但我正在努力解决这一问题 #include <stdio.h> int main () { int x, total; total = 0; x = 0; while (x <= -2 || x >= 0) { printf("Please ente

对于我正在尝试编写的程序,我必须创建一个程序,要求用户输入一个数字,并计算输入的所有数字的总数,直到用户输入-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;
}
#包括
int main()
{
int x,总计;
总数=0;
x=0;
while(x=0)
{
printf(“请输入一个数字:”);
scanf(“%d”和&x);
printf(“您输入了%d\n”,x);
totalSum=总计+x;
printf(“总计为%d\n”,总计);
}
printf(“祝您愉快:)\n”);
printf(“总计为%d\n”,总计);
返回0;
}

关于如何在-1处停止循环而不打印或将其添加到总数中的任何建议?

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

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

    if (-1 == x)
      break;

     ...
 }
我很抱歉,但是当我看到一个
而(1)
循环完全由条件中断驱动时,我会退缩。比如说:

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

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

这种方法的一个缺点是打印是重复的,但我相信使用while条件的pro实际上驱动了循环,而不是弥补它。另一个好处是,这里还检查了scanf,以确保它正确读取下一个值。

哦,所以我需要添加条件来中断循环?谢谢你,分析一下,我越来越清楚了。