话不多说,上代码!!!
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
//将猜数范围的最大值和最小值进行常量定义
#define MAX_NUMBER 100
#define MIN_NUMBER 0
//初步声明变量
int MakeNumber();
int IsValidNum(const int number);
int IsRight(const int number ,const int guess);
void GuessNumber(const int number);
//主函数实现
int main()
{
//变量声明
int number;
char reply;
//为rand()函数设置随机种子数
srand(time(NULL));
do{
number = MakeNumber();
printf("请在0-100之间进行猜数\n");
GuessNumber(number);
printf("Do you want to continue(Y/N or y/n)?");
scanf(" %c",&reply);
}while(reply == 'Y' || reply == 'y');
return 0;
}
//猜数操作
void GuessNumber(const int number){
int count = 1;//猜数次数定义为1
int f2;
do{
int guess;
scanf("%d",&guess);
int f1 = IsValidNum(guess);
if(f1 == 1){
count++;
f2 = IsRight(number,guess);
}
}while(f2 != 1 && count <= 10);//判断是否已猜数正确并且次数是否超过10次
if(f2 == 1){
printf("Congratulation!You're so cool\n");
}
else if(f2 == 0)
{
printf("Mission failed after 10 attempts.\n");
}
}
//生成随机数
int MakeNumber(){
int number ;
number = (rand() % (MAX_NUMBER - MIN_NUMBER + 1) ) + MIN_NUMBER;//生成随机数的最大值为MAX_NUMBER,最小值为MIN_NUMBER
return number;
}
//判断输入的数据是否合法
int IsValidNum(const int number)
{
if(number >= MIN_NUMBER && number <= MAX_NUMBER)
return 1;
else
return 0;
}
//判断猜数是否正确
int IsRight(const int number ,const int guess){
if(guess < number){
printf("Wrong! Too small!\n");
return 0;
}else if(guess > number){
printf("Wrong! Too big!\n");
return 0;
}
else return 1;
}
如果觉得《C语言数据结构猜数小游戏》对你有帮助,请点赞、收藏,并留下你的观点哦!