c - Do While 循环的一个小问题

标签 c loops while-loop

所以我正在编写一个基本程序,要求用户输入一个数字,循环将继续,直到他们输入某个数字。 (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/

相关文章:

c - scanf inside while循环只工作一次

c++ - C++ 中的 Mpeg 7 描述符

c - 尝试使用 C 来理解 USB

c - do while 循环问题

php - 数组重复信息

java - 获取数组中项目的索引

c - 试图理解 C 中的 extern

c - 读取BMP文件并旋转

arrays - 在 Twig 中循环两个数组

python - 高效地迭代 pandas.DataFrame,同时一次访问多个索引行