为什么我在循环中使用随机数时得到相同的结果

Why am I getting the same results when using random numbers in a loop?

本文关键字:结果 随机数 循环 为什么      更新时间:2023-10-16

我可能是盲目的,尽管使用随机数,但每次运行这个控制台应用程序都得到相同的结果。谁能解释一下我哪里出错了?下面是代码:

#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <stdio.h>
using namespace std;
bool bacteria(long mut, long chance){
        bool result;
    if (mut >= chance){
         result = true;
    }
    else{
        result = false;
    }
    return result;
}
int run = 1000000;//Number of iterations
int mutations;
int survival;
void domutation(){
    mutations = 0;
    survival = 0;
    for (int i = 0; i < run; i++){
        long x = rand() % 2;
        long y = rand() % 1000000;
        bool run = bacteria(x, y);
        if (run == true){
            mutations++;
        }
        else if (run == false) {
            survival++;
        }
    }
    cout << "Mutations: " << mutations << "   Survivals: " << survival << endl;
}
int main(){
    for (int x = 0; x < 10; x++){
        domutation();
    }
    int wait;
    cin >> wait;
}

每次迭代的domation()产生不同于前一次迭代的结果,但每次运行应用程序时,结果总是与上次运行时相同,例如,第一次迭代总是产生38个突变,最后一次迭代总是产生52个突变,两者之间的所有都不变。

我肯定我在做一些愚蠢的事情!

我在Windows 8.1的VS 2013中工作。

谢谢!

rand给出了一个可预测的数字流。您需要对它进行种子设置,以便在该流中选择一个不同的点开始。假设你的程序每秒运行不超过一次,那么当前时间就是一个便宜/容易的种子。

int main(){
    srand(time(NULL));
    for (int x = 0; x < 10; x++){
        domutation();
    }

请注意,不提供种子相当于始终以srand(0)

启动程序。