我必须编写一个 do while 循环来读取整数并计算它们的总和。它会继续添加整数,直到用户输入 -1,但不应将 -1 添加到总和中。
do
{
printf("Enter a number. Enter -1 to stop\n");
scanf(" %d", &n);
sum = sum + n;
printf("The sum is %d\n", sum);
}
while (n >= 0);
{
return 0;
printf("Have a nice day!\n");
}
我哪里错了?如何获得 -1 以避免被添加到总和中?
最佳答案
使用前需要声明n
,i
。当检测到输入 -1 时,您需要一个 break
。
int sum = 0, n = 0;
do
{
printf("Enter a number. Enter -1 to stop\n");
scanf("%d", &n);
if( -1 == n )
break; // <-- break here to get out the loop
sum = sum + n;
printf("The sum is %d\n", sum);
} while (1); // <-- note while(1) should be used instead of while(n >= 0), this makes sure your loop only exits when detecting input -1
此外,在您return
之后添加printf
是没有意义的 - 即可以删除此代码:
{
return 0;
printf("Have a nice day!\n"); // <-- any code after `return` is meaningless
}
关于c - 在 do-while 语句中添加整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736239/