srand在C ++中太慢,返回相同的数字 [英] srand is too slow in C++ it return same number

查看:188
本文介绍了srand在C ++中太慢,返回相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图有一个简单的RndInt(limit)函数,它将返回一个限制为limit的随机数。

I'm just trying to have simply RndInt(limit) function that will return random numbers with a limit as limit.

    cout << "Enter higher limit of random range:" ;
 cin >> limit;
 while(limit != 0)

{
//        RndInt(limit);
    cout << "Random number smaller than " << limit << " is " << RndInt(limit) << endl;
    cin.get();
    cin.get();
    cout << "Other random number smaller than " << limit << " is " << RndInt(limit) << endl;
    cin.get();
    cin.get();
    cout << "There is " << RndInt(limit) << " ways I love you" <<endl ;
    cout << "Enter higher limit of random range:" ;
    cin >> limit;
}
return 0;
}

int RndInt(int limit)
{
srand(time(&base));
int rndnumber;
rndnumber=rand()%limit;
base+=100;
return rndnumber;
}

我有问题,使RndInt后续调用显示不同的整数。当我调试它对RndInt(limit)的精细后续调用给出不同的值。但是当我试图运行它没有cin.get()暂停,我得到相同的数字在所有三个调用。我发现问题是种子在同一秒钟。

I'm having problem to make RndInt subsequent calls display different integer. When I debug its fine subsequent calls to RndInt(limit) give different value. But when I try to run it without cin.get() for pause I get same numbers in all three calls. I figured out that problem is that seed is in the same second.

我的问题是如何使调用RndInt返回不同的值没有暂停。

My question is how to make calls to RndInt return different values without pause. What to do to srand function ?

推荐答案

不要调用 srand()每次你想要一个随机数。在程序开始时调用 srand() 一次,然后调用 rand()每个号码。

Do not call srand() every time you want a random number. Call srand() once at the start of your program, and then call rand() for each number.

这篇关于srand在C ++中太慢,返回相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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