猜数字游戏
编写一个猜数字程序,难度有三级。
从第一级到第三级,数字分别位于1~10,1~100,1~1000.
首先提示玩家选择难度,然后启动游戏。
计算机会在相应区间内生成一个随机数,让玩家来猜。
每当玩家做出猜测之后,给玩家一个线索,提示输出数字是大了还是小了。
计算机应记录所猜次数。
一旦玩家猜对则显示玩家所猜次数,并询问玩家是否要继续玩。
事例输出:
Let’s play Guess the Number.
pick a difficultly level(1,2or3):1
I have my number. What’s you guess? 1
Too low. Guess again: 5
Too high..Guess again:2
You got it in 3 guess!
play again? n
Goodbye!
挑战:
将所猜的次数对应如下评语:
猜1次:“You’re a mind reader!”
猜2~4次:“Most impressive.”
猜5!6次:“You can do better than that!”
猜7次以上:“Better luck next time.”
记录之前猜过的数字,如果用户再次输入,则警告已经猜过这个数。
这也算一次错误的猜测。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
//随机数生成函数
int New_a_Num(int n)
{
int tag = 1,i;
for (i = 0; i < n; i++)
{
tag *= 10;
}
//调用随机数生成函数
srand(time(NULL));
return rand()%tag;
}
//猜数字游戏函数
void Guess_the_Num()
{
int level,num,ans,cnt,past[1000],i;
char tag='n';
printf("Let's play Guess the Number !\n");
while (1)
{
printf("Pick a difficulty level(1,2or3):");
while (1)
{
scanf("%d",&level);
if (level > 3 || level < 1)
{
printf("Input Error!\nPlease input again!\n");
}
else
{
break;
}
}
//调用随机数生成函数,生成所需随机数
num = New_a_Num(level);
printf("I have my number. What's your guess?");
cnt = 0;//初始化计数器
//初始化past数组
for (i = 0; i < 1000; i++)
{
past[i] = 0;
}
while (1)
{
scanf("%d",&ans);
if (!past[ans])//如果第一次输入该数字,记录该数字
{
past[ans] = 1;
if (ans < num)
{
printf("Too low.Guess again:");
cnt++;
}
else if (ans > num)
{
printf("Too high.Guess again:");
cnt++;
}
else
{
printf("You got it in %d guess!\n", cnt);
break;
}
}
else
{
printf("Input Error!\n");
}
}
if (cnt < 2)
{
printf("You are a mind reader!\n");
}
else if (cnt < 4)
{
printf("Most imporssive!\n");
}
else if (cnt < 6)
{
printf("You can do better than that!\n");
}
else
{
printf("Good Luck next time!\n");
}
printf("Play again?");
scanf("\n%c",&tag);
if (tag=='n')
{
printf("Good bye!\n");
break;
}
}
}
int main(void)
{
Guess_the_Num();
system("pause");
return 0;
}