随机整数似乎总是相同的
C++ Random integer seems to always be the same
对于我当前的项目,我已经创建了一个事件,应该根据我的代码生成的随机整数而改变,唯一的问题是我似乎总是得到相同的路径。简而言之,我希望这两个事件发生的概率都是50%。谢谢,西蒙
random1 = rand() % 1 + 0;
if (random1 == 0) {
int choice4;
cout << "Your character screams at the top of his lungs, " << endl;
cout << "this causes the dragon to immediately to bow in fear..." << endl;
cout << "It turns out dragons are very sensitive to hearing....." << endl;
system("pause");
cout << "nIt seems the dragon is requesting you ride it!n" << endl;
cout << "Will you ride it?n" << endl;
cout << "1. Ride it" << endl;
cout << "2. Or Wait here." << endl;
cin >> choice4;
cin.ignore();
system("cls");
if (choice4 == 1){
Ending();
}
}
else if (random1 == 1) {
cout << "Your character screams at the top of his lungs, " << endl;
cout << "eventually your breath gives out and you die because of lack of oxygen." << endl;
system("pause");
gameover();
到目前为止,所有其他答案都提到需要使用srand()
来初始化随机数生成器,这是一个有效的点,但不是您遇到的问题。
你的问题是你的程序计算你的随机数和1的模,它总是等于0,因为对于任何整数n,
n % 1 == remainder of the integer division of n by 1
== n - (n / 1)
== 0
那么,替换这个:
random1 = rand() % 1 + 0;
与这个:random1 = rand() % 2;
,你就会得到你想要的东西。我说"有点"是因为还有其他问题需要考虑,例如随机数生成器初始化(srand()
),使用rand()
而不是更复杂的rng等。
rand()只能生成伪随机数,即相同的种子会生成相同的序列。
只需使用srand()来初始化种子,下面是一个示例
#include <cctype>
#include <sys/time.h>
struct timeval cur_tm;
gettimeofday(&cur_tm, NULL);
seed = static_cast<unsigned int>(cur_tm.tv_usec);
srand(seed);
相关文章:
- 生成线性随机整数C++
- 如何生成 0 到 0x7FFFFFFF 的随机整数?
- 生成随机整数
- C++:随机数列表:x 个随机整数
- C++带有权重的随机非重复整数
- 列出小于 10 的不同随机整数
- 在 c++ 中生成随机整数
- C++随机函数给出的相同整数是输出的两倍
- 取消随机排列整数/字符数组
- 随机选择 2 个不在范围内的整数
- 我将如何防止整数在随机发生器中多次生成
- C++ 通过 range for 循环将整数输入到矢量中;随机 0
- 随机整数仍在生成低于或高于范围的数字?
- C++,为什么我不能使用两个默认随机引擎生成独立的随机整数样本
- 在 C++ 中使用 10 个随机整数的数组进行气泡排序不起作用
- C++ 如何生成 10,000 个 UNIQUE 随机整数以存储在 BST 中?
- 如何将唯一的随机整数插入链表中
- 伪随机整数
- 生成伪随机16位整数
- 使用boost::random库获取整数随机值而不是实数