zoukankan      html  css  js  c++  java
  • C++生成随机数

    代码实现了使用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 }
  • 相关阅读:
    第02组 Alpha冲刺 (6/6)
    面向对象分析设计考试复习【历年卷】
    第02组 Alpha冲刺 (5/6)
    第02组 Alpha冲刺 (4/6)
    第02组 Alpha冲刺 (3/6)
    第02组 Alpha冲刺 (2/6)
    第02组 Alpha冲刺 (1/6)
    linux内核结构
    从别人的博客学习
    递归的认识
  • 原文地址:https://www.cnblogs.com/Jesse-Cavendish/p/11615768.html
Copyright © 2011-2022 走看看