c++-猜数字,随机数的生成

#include <iostream>
#include <ctime>
using namespace std;

int main7() {
	srand((unsigned int)time(NULL));
	int num = rand() % 100 + 1;
	int i;
	while (1) {
		cout << "请输入一个数:" << endl;
		cin >> i;
		if (i < num) {
			cout << "太小啦!" << endl;

		}
		else if (i > num) {
			cout << "太大了!" << endl;

		}
		else  {
			cout << "对啦!" << endl;
			break;
		}
	}
	return 0;
}

框架:首先出一个随机数,然后让玩家输入一个数字,判断是否相等,循环到猜到对的数字

语法:判断用if,循环用while,不用for语句,因为for要有三个条件,while语句只用一个条件。

while语句语法:while(表达式判断or写1会死循环){(写break跳出循环)}

最主要的是系统生成随机数的写法

要每次出不同的数要建立种子库

添加随机数种子,用当前系统时间生成,建立头文件

#include<ctime>

然后在main函数里写生成随机数的代码

sand((unsigned int)time(NULL));

int num = rand ()%100  //范围在0-99,单写这个只会每次生成一样的数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值