我必须编写一个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
然后再使用。并且break
在检测输入-1时需要一个。
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
另外,printf
在您之后添加a也没有意义return
-即可以删除此代码:
{
return 0;
printf("Have a nice day!\n"); // <-- any code after `return` is meaningless
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句