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

C在循环内生成随机数

发布时间:2020-12-16 09:59:34 所属栏目:百科 来源:网络整理
导读:我想在循环内生成随机数,但结果总是相同的数字. 我做错了什么?谢谢. 码 #include fstream#include ctime#include cstdlibusing namespace std;const char duom[] = "U1.txt";const char rez[] = "U1_rez.txt";void num_gen(int x,int y);int main(){ srand(
我想在循环内生成随机数,但结果总是相同的数字.
我做错了什么?谢谢.

#include <fstream>
#include <ctime>
#include <cstdlib>

using namespace std;

const char duom[] = "U1.txt";
const char rez[] = "U1_rez.txt";

void num_gen(int & x,int & y);

int main(){
    srand(time(NULL));

    int x,y;

    ifstream fd(duom);
    fd >> x >> y;
    fd.close();

    ofstream fr(rez);
    for(int j = 1; j <= 4; j++){
        num_gen(x,y);
        fr << x << " + " << y << " = "<< x + y << endl;
        fr << x << " - " << y << " = "<< x - y << endl;
        fr << x << " * " << y << " = "<< x * y << endl;
        fr << x << " / " << y << " = "<< x / y << endl;
        fr << "************" << endl;
    }
    fr.close();
    return 0;
}

void num_gen(int & x,int & y){
     x = 3 + (rand() % 10);
     y = 3 + (rand() % 10);
}

结果

4 8 = 12
4 – 8 = -4
4 * 8 = 32
4/8 = 0
************
4 9 = 13
4 – 9 = -5
4 * 9 = 36
4/9 = 0
************
9 11 = 20
9 – 11 = -2
9 * 11 = 99
9/11 = 0
************
12 8 = 20
12 – 8 = 4
12 * 8 = 96
12/8 = 1
************

解决方法

随着C 11/14的出现,你应该放弃使用srand&兰德&使用标题#include< random>中声明的更高效的随机数生成机器.以一个简单的例子说明: –

#include <iostream>
#include <random>   // for default_random_engine & uniform_int_distribution<int>
#include <chrono>   // to provide seed to the default_random_engine
using namespace std;

default_random_engine dre (chrono::steady_clock::now().time_since_epoch().count());     // provide seed
int random (int lim)
{
    uniform_int_distribution<int> uid {0,lim};   // help dre to generate nos from 0 to lim (lim included);
    return uid(dre);    // pass dre as an argument to uid to generate the random no
}

int main()
{
    for (int i=0;i<10;++i)
    cout<<random(10)<<" ";
    return 0;
}

上述代码的其中一项输出是: –

8 5 0 4 2 7 9 6 10 8

请参阅,数字从0到10不等.根据您所需的输出,在uniform_int_distribution中给出限制.这件事很少失败&你可以在更大的范围内生成随机数,而不必担心像你那样令人难以置信的输出.

(编辑:李大同)

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

    推荐文章
      热点阅读