簡體   English   中英

C ++在循環內生成隨機數

[英]C++ generating random numbers inside loop

我想在循環內生成隨機數,但結果總是相同的數字。
我做錯了什么? 謝謝。

#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的出現,您實際上應該放棄使用srandrand並使用標頭#include<random>聲明的更高效的RANDOM NUMBER GENERATING MACHINES。 以一個簡單的例子說明: -

#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給出限制。 這件事很少失敗,你可以在更大的范圍內生成隨機數,而不必像你那樣擔心令人發指的輸出。

可能是因為隨機方法隨着計算機的運行而運行。 因此,如果在相同的1/10000秒內,您的計算機執行了他需要執行的所有操作,您可能會讀取相同的數字,因為隨機方法沒有刷新該值。 嘗試在for的結尾處for sleep(100)sleep(100) )並檢查值是否已更改。

我認為你的代碼應該在每次運行時產生3到12之間的不同“偽”隨機數,這取決於每次運行之間經過了一秒鍾。 檢查這一切是否真的是你想要的。

也許你只是在調用time(NULL)時比運行時間快得多,這會返回自紀元以來的秒數。

無論如何,你的隨機數不是很好,因為你使用低階位。 我在rand()手冊頁中記錄了這段摘錄:

In  Numerical Recipes in C: The Art of Scientific Computing (William H.
       Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New
       York:  Cambridge University Press, 1992 (2nd ed., p. 277)), the follow-
       ing comments are made:
              "If you want to generate a random integer between 1 and 10,  you
              should always do it by using high-order bits, as in

                     j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));

              and never by anything resembling

                     j = 1 + (rand() % 10);

              (which uses lower-order bits)."

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM