加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C语言中随机函数发生器rand()用法举例

发布时间:2020-12-16 07:45:07 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 #if 1#include stdlib.h#include stdio.h#include time.h#include iostream#include fstreamusing namespace std;int main(){ int nRandNumber[10]; f

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

#if 1
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int nRandNumber[10];
    for (int idx = 0; idx < 10; ++idx)
    {
        nRandNumber[idx] = rand();//取随机数范围为integer 0 ~ RAND_MAX(32767)
        cout << nRandNumber[idx] << endl;
    }
    for (int idx = 0; idx < 10; ++idx)
    {
        nRandNumber[idx] = (double)rand() / (RAND_MAX + 1) * (125 - 35) + 35;//取数35到125之间
        cout << nRandNumber[idx] << endl;
    }
    cout << RAND_MAX << endl;//最大值是32767
 
     
    //srand是一个随机数种子产生函数,当参数为1时,所得到的随机数序列一样
    //output : nRanNum1 : 41 nRanNum2 : 18467
    //         nRanNum3 : 41 nRanNum4 : 18467
    ofstream outFile("d:out.txt");
 
    srand(1);
    int nRanNum1 = rand();
    int nRanNum2 = rand();
 
    cout << "nRanNum1 : " << nRanNum1 << " nRanNum2 : " << nRanNum2 << endl;
     
    outFile << "nRanNum1 : " << nRanNum1 << " nRanNum2 : " << nRanNum2 << endl;
    srand(1);
    int nRanNum3 = rand();
    int nRanNum4 = rand();
    cout << "nRanNum3 : " << nRanNum3 << " nRanNum4 : " << nRanNum4 << endl;
    outFile << "nRanNum3 : " << nRanNum3 << " nRanNum4 : " << nRanNum4 << endl;
     
    system("pause");
    return 1;
     
}
#endif

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读