C语言用折中法写猜数字代码
时间: 2023-05-19 13:05:37 浏览: 56
以下是使用折中法写的猜数字代码:
```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;
}
```
希望能对你有所帮助!
相关问题
C语言用穷举法写猜数字代码
以下是C语言用穷举法写猜数字代码的示例:
#include <stdio.h>
int main() {
int answer = 42; // 答案为42
int guess = 1; // 初始猜测为1
while (guess != answer) {
printf("请猜一个数字:");
scanf("%d", &guess);
if (guess < answer) {
printf("猜小了!\n");
} else if (guess > answer) {
printf("猜大了!\n");
} else {
printf("恭喜你,猜对了!\n");
}
}
return 0;
}
使用c语言写猜数字游戏代码
以下是一个简单的猜数字游戏的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num, guess, tries = 0;
srand(time(0)); // 设置随机数种子
num = rand() % 100 + 1; // 生成1-100之间的随机数
printf("猜数字游戏:猜一个1-100的数字\n");
do {
printf("请输入你的猜测:");
scanf("%d", &guess);
tries++;
if(guess > num) {
printf("太大了!\n");
}else if(guess < num) {
printf("太小了!\n");
}else {
printf("恭喜你,猜对了!你用了%d次尝试。\n", tries);
}
}while(guess != num);
return 0;
}
```
程序会生成一个1-100之间的随机数,然后要求用户猜测这个数字。如果用户猜的数字太大或太小,程序会提示用户继续猜测。如果用户猜对了,程序会输出恭喜信息,并告诉用户猜了多少次才猜对。