gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:54 26 4
gpt4 key购买 nike

我需要以一种有效的方式找到一个由用户在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com