C语言用折中法写猜数字代码
时间: 2023-05-19 18:05:37 浏览: 91
用C语言写的猜数字程序
以下是使用折中法写的猜数字代码:
```c
#include <stdio.h>
int main() {
int low = 1, high = 100, guess;
printf("请在1到100之间想一个数字,我来猜:\n");
while (low <= high) {
guess = (low + high) / 2;
printf("我猜这个数字是%d,对吗?\n", guess);
int response;
printf("请输入1表示猜对了,-1表示猜小了,0表示猜大了:");
scanf("%d", &response);
if (response == 1) {
printf("太好了,我猜对了!\n");
break;
} else if (response == -1) {
low = guess + 1;
} else {
high = guess - 1;
}
}
return 0;
}
```
希望能对你有所帮助!
阅读全文