srand在C++中速度太慢,它返回相同的数字
srand is too slow in C++ it return same number
我只是想有一个简单的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()
。
相关文章:
- 函数如何使用引用返回所需的数字?
- 如何优化代码以返回最接近给定整数的数字,但给定列表中不存在?
- 返回 int 中可被 2 c++ 整除的所有数字的总和
- C++ python 中的函数返回数字而不是字符串
- 使用非托管导出将字符串从 C# 返回到C++将返回数字
- 我的代码应该接受一个数字,并返回字母等级或"Grade is not valid"但 else 语句不起作用
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 将 MPFR 数字转换为字符串并返回
- C++ 递归:返回数字的最小偶数
- typeid.name 返回派生类类型之前的数字
- Fibbonaci 递归代码返回错误值,始终返回下一个数字
- 为什么我的阶乘数查找器返回以C++输入的数字?(已编辑)
- 将字符转换为ASCII返回数字太大
- 从排序的数字数组中返回数字范围的最快方法是什么?
- 使用关键字从文本文件返回数字
- 将元组传递给函数并让它返回数字列表的最佳方法
- placeNumbers应该返回数字的顺序,以便满足布尔值向量中编码的条件
- 带有Overload[]运算符的C++MyInteger类,因此索引在位置i返回数字
- c++程序返回数字而不是字符
- 返回数字所在的行