c++实现while循环语句,生成随机数,猜数字游戏

while循环语句

在屏幕中打印0~9这十个数字

#include<iostream>
using namespace std;
int main() {
	/*
	while循环语句:满足循环条件,执行循环语句
	语法:while(循环条件){循环语句}
	只要循环条件的结果为真,就执行循环语句
	*/
	//在屏幕中打印0~9这十个数字
	int num = 0;
	while (num <= 9)
	{
		cout << num << endl;
		num++;
	}
	system("pause");
	return 0;
}

生成随机数

#include<iostream>
using namespace std;
int main() {
	//猜数字:系统随机生成一个1-100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果才对恭喜玩家胜利,并且退出游戏
	int num = rand() % 100 + 1;//系统随机生成一个1-100之间的数字
	cout << num << endl;
	int num1 = rand() % 100 + 1;//系统随机生成一个1-100之间的数字
	cout << num1 << endl;
	int num2 = rand() % 100 + 1;//系统随机生成一个1-100之间的数字
	cout << num2 << endl;
	system("pause");
	return 0;
}

生成随机数截图

猜数字

:系统随机生成一个1-100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果才对恭喜玩家胜利,并且退出游戏。

#include<iostream>
using namespace std;
int main() {
	//猜数字:系统随机生成一个1-100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果才对恭喜玩家胜利,并且退出游戏
	int num = rand() % 100 + 1;//系统随机生成一个1-100之间的数字
	int a = 0;
	cout << "请输入一个数字" << endl;
	cin >> a;
	while (a != num)
	{
		if (a > num)
		{
			cout << "您输入的数字偏大,请重新输入:" << endl;
			cin >> a;
		}
		else if (a < num)
		{
			cout << "您输入的数字偏小,请重新输入:" << endl;
			cin >> a;
		}
	}
	cout << "恭喜你猜对了!" << endl;

	system("pause");
	return 0;
}

在这里插入图片描述
但是,此代码优缺点,每次生成的随机数都是42。
为了解决这个问题,要添加一个随机数种子,是利用当前系统时间生成随机数,防止每次随机数都一样。

#include<iostream>
#include<ctime>//随机数头文件
using namespace std;
int main() {
	//猜数字:系统随机生成一个1-100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果才对恭喜玩家胜利,并且退出游戏

	srand((unsigned int)time(NULL));//添加随机数种子,作用是利用当前时间生成随机数,防止每次随机数都一样

	int num = rand() % 100 + 1;//系统随机生成一个1-100之间的数字
	int a = 0;
	cout << "请输入一个数字" << endl;
	cin >> a;
	while (a != num)
	{
		if (a > num)
		{
			cout << "您输入的数字偏大,请重新输入:" << endl;
			cin >> a;
		}
		else if (a < num)
		{
			cout << "您输入的数字偏小,请重新输入:" << endl;
			cin >> a;
		}
	}
	cout << "恭喜你猜对了!" << endl;

	system("pause");
	return 0;
}

改进生成随机数部分

改进猜数字游戏:

添加游戏次数

#include<iostream>
#include<ctime>//随机数头文件
using namespace std;
int main() {
	//猜数字:系统随机生成一个1-100之间的数字,玩家进行猜测,如果猜错,提示玩家数字过大或过小,如果才对恭喜玩家胜利,并且退出游戏
	srand((unsigned int)time(NULL));//添加随机数种子,作用是利用当前时间生成随机数,防止每次随机数都一样

	int num = rand() % 100 + 1;//系统随机生成一个1-100之间的数字
	int a,count = 0;
	//int count = 0;
	cout << "请注意:本次游戏共5次机会!" << endl;
	cout << "请输入一个数字" << endl;
	cin >> a;
	while (a != num)
	{
		if (a > num && count < 4)
		{
			cout << "您输入的数字偏大,请重新输入:" << endl;
			cin >> a;
			count = count + 1;
		}
		else if (a < num && count < 4)
		{
			cout << "您输入的数字偏小,请重新输入:" << endl;
			cin >> a;
			count = count + 1;
		}
		else
		{
			cout << "本次游戏五次机会已经用完,游戏失败! " << endl;
			break;
		}
	}
	if (a == num)
	{
		cout << "恭喜你猜对了!" << endl;
	}
	

	system("pause");
	return 0;
}

改进游戏次数

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值