为什么以下代码失败? [英] Why does the following code fail?

查看:82
本文介绍了为什么以下代码失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么以下代码失败。我认为每次调用random()函数时它都会产生一个新的数字,尽管是递归的。但似乎这个数字在改变之前已经很长时间保持静止。为什么会这样?如何更改它以便每次调用时都会生成一个新数字?



非常感谢!



我尝试过:



I am wondering why the following code fail. I thought it will generate a new number every time the random() function is called, albeit recursively. But it seems that the number remains stationary for a pretty long time before changing. Why is that the case? And how can I change it so that every time it is called, a new number will be generated?

Thanks a lot!

What I have tried:

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

int i=0;
int random();

int main(){
    random();
    return 0;
}

int random(){
    int a;
    i+=1;
    srand(time(NULL));
    a=rand()%20;
    printf("This is the %d th iteration\n",i);
    printf("random number generated is: %d\n",a);
    if(a<8)
        random();
}

推荐答案

Google是你的朋友......你需要做一些研究并学习如何使用rand功能正确... c rand number [ ^ ]



从上面的谷歌搜索: C库函数 - rand() [ ^ ]

Google is your friend ... you need to do some research and learn how to use the rand function properly... c rand number[^]

From the google search above: C library function - rand()[^]
#include <stdio.h>
#include <stdlib.h>

int main()
{
   int i, n;
   time_t t;
   
   n = 5;
   
   /* Intializes random number generator */
   srand((unsigned) time(&t));

   /* Print 5 random numbers from 0 to 19 */
   for( i = 0 ; i < n ; i++ ) 
   {
      printf("%d\n", rand() % 20);
   }
   
   return(0);
}


尝试

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

int i=0;
int random();

int main(){
    srand(time(NULL));
    random();
    return 0;
}

int random(){
    int a;
    i+=1;
    a=rand()%20;
    printf("This is the %d th iteration\n",i);
    printf("random number generated is: %d\n",a);
    if(a<8)
        random();
}



问题在于srand()。随机数生成器不是随机的,它是pseufo-random,这意味着如果你用相同的值设置种子2次,你将获得相同的随机序列。因为你的种子是几秒钟,所以你每次都得到相同的序列。


The problem is with srand(). the random number generator is not random, it is pseufo-random, it means that if you set the seed 2 times with same value, you will get the same 'random' sequence. And since your seed is a number of seconds, you get every time the same sequence.


这篇关于为什么以下代码失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆