c - while 循环在每次迭代中工作两次

标签 c loops while-loop

我需要以有效的方式找到用户在 1 到 1000 之间确定的数字。看起来它正在工作,但我有一个问题。每当 while 循环迭代时,它都会迭代两次,我无法摆脱这种情况。所以我不能称之为“完全”工作。我的代码是:

#include <stdio.h>

int main()
{
    int num = 500, div = 250;
    char user;

    printf("Please determine a number between 1 and 1000 and then press enter. \n");

    scanf("%c", &user);

    while ((user != 'Y') && (user != 'y'))
    {
        printf("Is your number %d? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger. \n", num);

        scanf("%c", &user);

        if ((user == 'S') || (user == 's')) {
            num -= div;
            if (div != 1)
                div /= 2;
        }

        if ((user == 'L') || (user == 'l')) {
            num += div;
            if (div != 1)
                div /= 2;
        }
    }

    printf("The number you determined is %d!", num);

    return 0;
}

如何解决这个问题?

编辑:我无法从 CodeBlocks 中放置输出示例,因此现在从 Ubuntu 添加它。输出如下:

Please determine a number and then press enter.

Is your number 500? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger. s

Is your number 250? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger.

Is your number 250? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger. s

Is your number 125? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger.

Is your number 125? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger. l

Is your number 187? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger.

Is your number 187? Please enter 'Y' if it is, 'S' if it is smaller and 'L' if it is larger. y

The number you determined is 187!

user3121023 已解决该问题。我认为既然这是一条评论,我就无法关闭这个问题。

最佳答案

scanf 的 %c 格式说明符将读取任何字符,包括空格。因此,下一次循环时,它会读取换行符并继续。

您需要在格式说明符中放置一个前导空格以吸收输入缓冲区中的换行符。

scanf(" %c", &user);

关于c - while 循环在每次迭代中工作两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35927265/

相关文章:

php - For 循环从 0001 而不是 1 开始

python - 输入不工作Python

c - MISRA-2012 违反规则 20.12 : misra_c_2012_rule_20_12_violation: macro parameter "val" is used in both expanded and raw forms

javascript - jquery递归函数中奇怪的无限循环错误

c - 使用 typedef 构建结构 - C

python - 如何遍历两个列表?

sql - 避免 SQL Server 中的 while 循环

c - 循环持续时间比预期检查空行的时间长

c - 如何在 C 中测量 DNS 查找时间

在 Windows 上使用 Tiny C Compiler 编译并运行 file.c