随机数实现猜数字游戏

C语言实现猜数字游戏

方法:使用随机数产生数字 1-100

效果:1、在输入一个数字以后提示猜大或猜小

           2、猜中后显示猜中,并返回猜的数字

           3、记录玩家猜的次数

           4、玩后选择是否继续玩

代码实现:

#include <stdio.h>
#include <stdlib.h>  //提供包含随机数种子的srand()和rand()函数
#include <time.h>  //提供时间,产生变化的随机数种子
#include <Windows.h>

int main()
{
    srand((unsigned int)time(NULL));  //创造随机数种子

	int num = 0;
	int guess = 0, sum = 0;
	bool chioce = true;
	while (chioce)
	{
		num = rand() % 100 + 1;  //使随机数的范围在1-100
		while (1)
		{
			printf("请猜数字(1 - 100):\n");
			scanf_s("%d", &guess); 
			sum++;  //输入猜的数字以后,记录猜的次数
			if (guess > num)
			{
				printf("猜大了!\n");
			}
			else if (guess < num)
			{
				printf("猜小了!\n");
			}
			else
			{
				printf("猜对了,猜了%d次, guess = %d !\n", sum, num);
				break;
			}
		}
		system("pause");
		system("cls");//清屏
		printf("继续猜? y / n \n");
		getchar();  //清除缓冲区内的'\n'
		char ch = getchar();
		if (ch != 'y' && ch != 'Y')
		{
			chioce = false;  //如果不选择继续,将循环条件置为假
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值