文章目录

  • 一、核心代码
  • 二、整个代码实现

一、核心代码

(1)随着系统时间,随机生成一个数字(头文件应引用#include )。

int s = rand() % 100 + 1;
	cout << "s=" << s << endl;

(2)循环的结构实现猜数字效果,附加一个条件判断来设置猜数字机会只有三次(防止无限循环)。

int t = 0;
	while (t < 3)
	{
		cin >> c;
		if (s == c)
		{
			cout << "恭喜你猜对了!" << endl;
			break;
		}
		else
		{
			if (c > s) {
				cout << "猜的数字太大了!" << endl;
			}
			if (c < s) {
				cout << "猜的数字太小了!" << endl;
			}
		}
		t++;
		if (t == 3) {
			cout << "游戏结束!"<<endl;
		}
		else
		{
			cout << "你还有" << 3 - t << "次机会" << endl;
		}
		continue;

二、整个代码实现

#include <iostream>
#include <string>
#include <ctime>
using namespace std;
int main()
{
	cout << "=======欢迎来到猜数字游戏======="<<endl;
	//随机生成一个数字
	srand((unsigned int)time(NULL));
	int s = rand() % 100 + 1;
	cout << "s=" << s << endl;
	int c;
	
	int t = 0;
	while (t < 3)
	{
		cin >> c;
		if (s == c)
		{
			cout << "恭喜你猜对了!" << endl;
			break;
		}
		else
		{
			if (c > s) {
				cout << "猜的数字太大了!" << endl;
			}
			if (c < s) {
				cout << "猜的数字太小了!" << endl;
			}
		}
		t++;
		if (t == 3) {
			cout << "游戏结束!"<<endl;
		}
		else
		{
			cout << "你还有" << 3 - t << "次机会" << endl;
		}
		continue;
		
	}
	system("pause");
	return 0;
}

更多推荐

C++编写一个猜数字游戏的代码