c - 为什么这个程序会卡住?
问题描述
我正在编写一个小玩具程序来猜测用户选择的数字,但是当我运行它时,它卡在了:
Is your number higher or lower? (h/l):
这是我到目前为止编写的代码:
#include <stdio.h>
#include <stdlib.h> // includes srand() and rand()
#include <time.h>
#define MAX 100
#define MIN 1
int main(void)
{
time_t t;
char response;
int lower = MIN, higher = MAX, guess;
srand(time(&t)); //Initializes random number generator
guess = (random() % 100) + 1; // Initial guess
printf("Pick a number from 1 to 100. I'll try to guess it.\n");
printf("Is your number %d? (y/n): ", guess);
while ((response = getchar()) != 'y')
{
printf("Is your number higher or lower? (h/l): ");
while ((response = getchar()) == 'h' || response == 'l')
{
if (response == 'h') {
lower = guess;
guess = (higher - guess) / 2;
printf("Is it %d?: ", guess);
} else if (response == 'l'){
higher = guess;
guess = (higher - guess) / 2;
printf("Is it %d?: ", guess);
}
}
}
printf("Great!!\n");
return 0;
}
由于某种原因,它没有进入第二个循环,在那里我检查是否response
等于h
或l
。
解决方案
好的,我找到了一种处理换行符的方法,并且仍然可以getchar()
用来获取输入:
#include <stdio.h>
#include <stdlib.h> // includes srand() and rand()
#include <time.h>
#define MAX 100
#define MIN 1
char get1stChar(void);
int main(void)
{
time_t t;
char response;
int lower = MIN, higher = MAX, guess;
srand(time(&t)); //Initializes random number generator
guess = (random() % 100) + 1; // Initial guess
printf("Pick a number from 1 to 100. I'll try to guess it.\n");
printf("Is your number %d? (y/n)\n"
"Or is it Higher or Lower (h/l): ", guess);
response = get1stChar();
while (response != 'y')
{
printf("you're here\n");
while (response == 'h' || response == 'l')
{
if (response == 'h') {
lower = guess;
guess = (higher - lower) / 2;
printf("Higher: %d, Lower: %d\n", higher, lower);
printf("Is it %d, higher or lower (y/h/l)?: ", guess);
} else if (response == 'l'){
higher = guess;
guess = (higher - lower) / 2;
printf("Higher: %d, Lower: %d\n", higher, lower);
printf("Is it %d, higher or lower (y/h/l)?: ", guess);
}
response = get1stChar();
}
}
printf("Great!!\n");
return 0;
}
char get1stChar(void)
{
char ch;
ch = getchar();
while ((getchar()) != '\n');
return ch;
}
推荐阅读
- python - 如何序列化objects.filter django的结果基于外键对象
- sql - 在 SQL 或 BigQuery 中将值“”转换为 null
- observable - RxJava:如何创建 rx.Single / rx.Observable 的任务图/工作流?
- windows-10 - 如何通过命令行为 Teradata 驱动程序设置 ODBC 连接?
- django - django ORM 与 asyncio
- java - @NotNull : 验证自定义消息不显示
- node.js - 无法使用节点和护照通过谷歌获取用户个人资料登录
- javascript - 无法直接在导出的模块上访问它
- java - 卡夫卡生产者巨大的内存使用量(泄漏?)
- opencv - Kinect v2 与 Openni 2 并与 OpenCV 3.1.0 一起显示