跳到正文

个人记录

如何造数据

zsfzyj约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年5月13日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

C++怎么批量做数据

C++
#include<bits/stdc++.h>
using namespace std ;
#define CNT 10
int R(){
    return rand() ;
}
void Ans(){

}
void Rand(){

}
int main(){
	char c[10001] ;
	srand(time(0)) ;
	for( int i = 1 ; i <= CNT ; i++ ){
		sprintf(c , "%d.in", i) ;//把整数i打印成i.in这个字符串,存在c中(如1 , c = "1.in")
		freopen(c , "w" , stdout) ;
 		Rand() ;
		fclose(stdin) ;
		sprintf(c , "%d.out", i) ;
		freopen(c , "w" , stdout) ;
		Ans() ;
		fclose(stdin) ;
	}
	return 0 ;
}

解释

建议大家用以上代码。因为不仅美观,还更容易将正解放进此代码。

首先先看R()函数,rand()是可以随机生成数,范围在0~32767(但还要加上srand(0),以保证每次的随机数不一样)。我们可以通过rand()来构成不同数的范围。

代码
如:
1~a :rand() % a+1
a~b :rand() % (b-a+1)+a
1~1000000 :(rand()%1000)*(rand()%1000)+1
0~1 :rand() / 100000.00000000

再看Rand()函数,将正解的输入全放这。再将变量的值赋值为R(),并输入到i.in文件中(严格按题目格式输入);

接着将正解代码中,主函数中剩余代码复制到Ans()中,若有其他函数,则直接在造数据代码中定义即可。

最后,想要造多少个数据点,改CNT即可。

例子

题目:输入两个整数 a,b,输出它们的和(∣a∣,∣b∣≤ 104 10^4 )。

正解(纯属为注意事项所作,不喜勿喷)

C++
#include<bits/stdc++.h>
using namespace std ;
int ans ;
void init(int a , int b){
	ans = a + b ;
}
int main(){
	int a , b ;
	cin >> a >> b ;
	init(a , b) ;
	cout << ans << endl ;
	return 0 ;
}

造数据代码

C++
#include<bits/stdc++.h>
using namespace std ;
#define CNT 10 // 造10个数据
int ans ;
int a , b ; // 要输入的变量为全局变量
void init(int a , int b){ //其他函数直接定义
  	ans = a + b ;
}
int R(){ // 范围:-10000~10000
	return rand() % 20001 - 10000 ;
    // return rand() % (10000-(-10000)+1) + (-10000);
}
void Ans(){ //主函数中剩余代码
	init(a , b) ;
	cout << ans << endl ;
}
void Rand(){ //正解的输入
	// cin >> a >> b ;
	a = R() , b = R() ;
	cout << a << " " << b << endl ;
}
int main(){
	char c[10001] ;
	srand(time(0)) ;
	for( int i = 1 ; i <= CNT ; i++ ){ // 处理第i个数据的文件。
		sprintf(c , "%d.in", i) ;
		freopen(c , "w" , stdout) ;
        Rand() ;
		fclose(stdin) ;
		sprintf(c , "%d.out", i) ;
		freopen(c , "w" , stdout) ;
        Ans() ;
		fclose(stdin) ;
	}
	return 0 ;
}
原文