用C语言编写猜数程序,程序中预先给定某个整数(例如100),用户从键盘反复输入整数进行猜数,每次输入数未猜中时,程序提示输入数过大或过小。猜中时是示猜的次数,最多允许猜3次。
时间: 2024-05-12 12:19:07 浏览: 90
关于猜数程序(C语言)
以下是一个简单的猜数程序示例:
```c
#include <stdio.h>
int main()
{
const int answer = 100; //预设答案
int guess, count = 0; //猜测的数和猜测次数
printf("Guess the number (0~999) in 3 tries:\n");
do {
printf("Guess #%d: ", count+1);
scanf("%d", &guess);
if (guess < answer) {
printf("Too low!\n");
} else if (guess > answer) {
printf("Too high!\n");
}
count++;
} while (guess != answer && count < 3);
if (guess == answer) {
printf("You got it in %d tries!\n", count);
} else {
printf("Sorry, you didn't guess the number. It was %d.\n", answer);
}
return 0;
}
```
程序中用 `const int answer = 100;` 预先设定了答案为100。然后用一个 `do-while` 循环来反复提示用户输入猜测的数,并根据输入的数和答案进行比较,输出相应的提示信息。如果猜对了,输出猜测的次数;如果猜错了三次,输出正确答案。注意猜测次数的计数要在循环中进行。
阅读全文