代碼實作了使用C++進行亂數的生成,其中NUMBER為所要生成的亂數的數量,RANGE為生成的亂數的范圍[0,RANGE],
生成的亂數會寫入同檔案夾下的random_number.txt檔案中,格式為每個數字占一行,
該代碼會在生成亂數的同時對生成亂數并完成寫入檔案所消耗的時間進行計算,
1 #include <iostream> 2 #include <fstream> 3 #include <cstdlib> 4 #include <ctime> 5 using namespace std; 6 #define NUMBER 100000 7 #define RANGE 1000 8 9 int main(void) 10 { 11 ofstream fout; 12 int x; 13 int i; 14 15 fout.open("random_number.txt"); 16 if(!fout){ 17 cerr<<"Can not open file 'random_number.txt' "<<endl; 18 return -1; 19 } 20 21 time_t start, end; 22 23 srand((unsigned)time(NULL)); //生成亂數種子 24 25 start=clock(); 26 27 for(i=0; i<NUMBER; i++){ 28 x= rand() % RANGE; //隨機生成1000以內的亂數 29 fout<<x<<endl; 30 } 31 32 fout.close(); 33 34 end=clock(); 35 36 cout<<"Successful Generation of Random Sequences!"<<endl; 37 38 cout<<"Time : "<<end-start<<endl; 39 40 return 0; 41 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/100181.html
標籤:C++
上一篇:插入排序
下一篇:背包問題
