C 解决猜数字游戏,由系统随机产生一个数字,然后用户输入一个数字来猜测
1、输入的数字比随机产生的大提示“Too big”,小了提示“Too small”
2、若在3次之内猜中了,输出“Good Guess”
3、超过N次没猜中,提示“Game Over”,在N次之前输入一个负数也提示“Game over”
思路:
用一个while(1)循环
(1)当猜测次数超过N次或输入负数时,break
(2)否则,根据猜测的数据输出相应的提示
代码:
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
#include<stdlib.h>
int main()
{
/*
* 猜数字游戏,由系统随机产生一个数字,然后用户输入一个数字来猜测
* 输入的数字比随机产生的大提示“Too big”,小了提示“Too small”
* 若在3次之内猜中了,输出“Good Guess”
* 超过N次没猜中,提示“Game Over”,在N次之前输入一个负数也提示“Game over”
*/
srand((unsigned)time(NULL)); // 为了每次产生的随机数不同
int random = rand() % 11 + 90; // rand() % a + b代表的时[b,a+b-1]之间的数字
int N = 10;
int count = 0;
int gussNum;
//printf("%d ", random);
while (1) {
scanf_s("%d", &gussNum);
count++;
if (count > N ) {
printf("Game Over,the remaining number of times is 0\n");
break;
}
if (gussNum < 0) {
printf("Game Over,input data is less than 0\n");
}
if (gussNum == random) {
if (N <= 3) {
printf("Good Guess,less than three times\n");
}
else {
printf("Guess is right,Game over,the total number of gusses is %d\n",count);
break;
}
}
else if (gussNum > random) {
printf("Too big,the remaining number of times is %d\n", N - count);
}
else {
printf("Too small,the remaining number of times is %d\n", N - count);
}
}
return 0;
}
运行结果截图: