srand在C++中速度太慢,它返回相同的数字

srand is too slow in C++ it return same number

本文关键字:返回 数字 C++ 速度 srand      更新时间:2023-10-16

我只是想有一个简单的RndInt(极限)函数,它将返回以极限为极限的随机数。

    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()暂停的情况下运行它时,我在所有三个调用中都得到了相同的数字。我发现问题是种子在同一秒。

我的问题是如何使对RndInt的调用不停顿地返回不同的值。如何处理srand函数?

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