新世纪小学20211014:生成随机数据

该博客介绍了如何使用C++生成随机数,以创建NOIP普及组计数问题的测试数据。通过`srand(time(0))`设置随机种子,然后利用`myrand()`函数产生指定范围内的随机整数,将数据写入文件`count.in`。同时,给出了读取这些数据并进行计数操作的源代码,输出结果到`count.out`。此外,还提供了批处理文件以循环执行数据生成和测试过程。
以2013NOIP普及组“计数问题”为例,解释如何生成随机数据
生成随机数据
#include <bits/stdc++.h>
using namespace std;

//生成一个范围在0~2147483647的随机数 
int myrand() {
	return (rand() << 16) + (rand() << 1) + (rand() & 1);
}

int main() {
	//播种:随机数种子 
	srand(time(0));
	
	//将产生的测试数据保存在count.in这份文件中 
	freopen("count.in", "w", stdout);
	
	//n的范围 [1,100] 
	int n = myrand() % 100 + 1;
	//x的范围[0,9] 
	int x = myrand() % 10;
	
	cout << n << ' ' << x << endl;

	return 0;
}
源代码
#include <bits/stdc++.h>
using namespace std;

int n, x, cnt;

int main() {
	freopen("count.in", "r", stdin);
	freopen("count.out", "w", stdout);
	
	cin >> n >> x;
	
	for (int i = 1; i <= n; i ++) {
		int t = i;
		
		while (t) {
			if (t % 10 == x) {
				cnt ++;
			}
			t /= 10;
		}		
	}
	cout << cnt << endl;

	return 0;
}
批处理文件运行测试脚本
@echo off

:loop

make_data.exe
type count.in

count.exe
type count.out

pause

goto loop
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值