为什么我在循环中使用随机数时得到相同的结果
Why am I getting the same results when using random numbers in a loop?
我可能是盲目的,尽管使用随机数,但每次运行这个控制台应用程序都得到相同的结果。谁能解释一下我哪里出错了?下面是代码:
#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)
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- valgrind-hellgrind与泄漏检查的结果不同
- 整数不会重复超过随机数
- 用C++20 fmt限制结果的总大小
- 如何返回一个类的两个对象相加的结果
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 序列化,没有库的整数,得到奇怪的结果
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 在更改for循环的第三部分后,未使用for循环结果
- if数组上的随机数
- 使用++运算符会导致意外的结果
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- 产生相同结果的随机数生成器
- C++随机数的逻辑运算结果
- 对于给定的密钥,什么样的随机数生成系统会只返回一个结果
- 为什么我在循环中使用随机数时得到相同的结果
- 随机数生成器给出一致的结果