返回非随机的结果

返回非随机的结果

本文介绍了调用RAND()返回非随机的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写掷硬币100000次,并计算多少尾巴多少头以及如何导致使用函数srand和兰特折腾了一个简单的C程序。以下是我有:

I am writing a simple C program that tosses a coin 100000 times and calculates how many heads and how many tails resulted from the toss using srand and rand. Here is what I have:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void){

    int i;
    int h=0;
    int t=0;
    int n;

    for(i=0;i<100000;i++){
        srand(time(NULL));
        n=rand()%2;
        if(n==0){
            h++;
        }
        else {
            t++;
        }
    }

    printf("%d heads\n", h);
    printf("%d tails\n", t);

    return EXIT_SUCCESS;
}

但是运行程序我有时会收到100000头和0尾,有时0头和100000尾巴,当有时我得到的头和尾巴,但不以任何方式为50%的头随机数50%的尾巴。

However when running the program I sometimes get 100000 heads and 0 tails and sometimes 0 heads and 100000 tails and sometimes I get random numbers in heads and tails but not in any way a 50% heads 50% tails.

我缺少的东西吗?
谢谢!

Am I missing something?Thanks!

推荐答案

正在围绕它的外表每次播种使用相同的种子的伪随机数发生器。只需将调用函数srand 外循环。

You are seeding the pseudo-random number generator with the same seed each time around the look. Simply move the call to srand outside the loop.

srand(time(NULL));
for(i=0;i<100000;i++){
    n=rand()%2;
    .....


一个(PRNG)是确定性的。也就是说,给定相同的初始种子,它会返回号码每次被调用的相同的序列。在您的code,因为你每次播种一次调用兰特,你得到的1号的循环每次迭代的顺序相同。现在,程序的不同执行将有不同的结果,因为时间将有变化。


A pseudo-random number generator (PRNG) is deterministic. That is, given the same initial seed, it will return the same sequence of numbers each time is is called. In your code, since you seed every time you call rand, you get the same sequence of 1 number for every iteration of your loop. Now, different executions of the program will have different results, because time will have changed.

而在当你没有看到100%的元首或100%尾巴的情况下,这将是在循环了足够长的时间来拥有先进的。

And in the cases when you were not seeing 100% heads or 100% tails, that would be when the loop took sufficiently long for time to have advanced.

这篇关于调用RAND()返回非随机的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:19