所以我正在编写一个基本程序,要求用户输入一个数字,循环将继续,直到他们输入某个数字。 (25)。然后程序会将他们输入的所有数字相加。问题是当我输入退出号时,循环没有退出,我不确定为什么。
double userNum = 0;
double sum = 0;
do {
printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n");
scanf("%f", &userNum);
sum = sum + userNum;
} while (userNum != 25);
printf("The sum of all the numbers you entered:%f\n", sum);
我也不确定总和是否会正确计算,因为我从未能够退出循环。
最佳答案
考虑使用 fgets 进行输入并使用 sscanf 解析该值。有了这个,您可以输入done或exit来终止循环,而不是25。扫描 double 的格式是%lf
。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( void)
{
char input[99] = "";
double userNum = 0;
double sum = 0;
while ( 1) {
printf("Please enter a number you would like to add [Enter 25 to exit at any time]:\n");
if ( ( fgets ( input, sizeof ( input) , stdin))) {
if ( strcmp ( input, "25\n") == 0) {//could use exit, done ... instead of 25
break;
}
if ( ( sscanf(input, "%lf", &userNum)) == 1) {//sscanf successful
sum = sum + userNum;
}
}
else {
break;//fgets failed
}
}
printf("The sum of all the numbers you entered:%f\n", sum);
return 0;
}
关于c - Do While 循环的一个小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822819/