用C实现猜数字游戏-CSDN博客

37 阅读1分钟
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
void game();
void menu();
int main()
{
	int xuan,ret;
	srand((unsigned int)time(NULL));
	do
	{
		menu();
		printf("请选择>");
		scanf("%d",&xuan);
		switch(xuan)
		{
			case 1:game();
			break;
			case 0:printf("退出游戏\n");
			break;
			default:printf("输入错误\n");
			break;
		}
		
	}while(xuan);
	return 0;
}



void menu()
{
	printf("###########################\n");
	printf("#### 1.play     0.exit ####\n");
	printf("###########################\n");
}

void game()
{
	int guess;
	int ret=rand()%100+1;

	while(1)
	{	printf("请猜数字>");
		scanf("%d",&guess);
		if(guess>ret)
		{
			printf("猜大了\n");
			
		}
		else if(guess<ret)
		{
			printf("猜小了\n");
		}
		else
		{
			printf("恭喜你!猜对了!\n");
			break;
		}
	}
	
	
}

这个代码的难点主要在于怎么生成随机数!

我调用了rand()函数 (#include<stdlib.h>)

time(NULL)函数   (#include<time.h>)

这些函数都需要日积月累!!!

相关使用说明可上网查询

注意srand()不要多次调用!!!所以把它放在主函数里面!!!