使用C语言写的猜数字游戏
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
//菜单 游戏选择
printf("****************************\n");
printf("********** 1.play **********\n");
printf("********** 0.exit **********\n");
printf("****************************\n");
}
void game()
{
//生成随机数(1-100)
//rand()%100 余数是0-99
int ret = rand() % 100 + 1;
//猜数字循环
int guess = 0;
int count = 5;//限制猜测次数
while (count)
{
printf("请猜数字:>");
scanf("%d",&guess);
if (guess < ret)
{
printf("猜小了!\n");
}
else if (guess > ret)
{
printf("猜大了!\n");
}
else
{
printf("恭喜你,猜对了!\n");
}
count--;
}
if (count == 0)
{
printf("猜失败了,正确的数字是%d:\n",ret);
}
}
int main()
{
int input = 0;
//srand()使用time()改变随机数种子
srand((unsigned int)time(NULL));
do {
menu();
printf("请选择-->");
scanf("%d",&input);
switch (input)
{
case 1:
game();
break;
case 0:
printf("退出游戏!\n");
break;
default:
printf("输入错误,请重新输入:");
break;
}
} while(input);
return 0;
}