我有一个包含 7 个元素的数组,我试图获得 0 - 6 之间的随机数,以便我可以随机选择数组中的一个元素。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Color{
public:
Color(){
colors[0] = "red";
colors[1] = "orange";
colors[2] = "yellow";
colors[3] = "green";
colors[4] = "blue";
colors[5] = "indigo";
colors[6] = "violet";
}
void printColors()
{
for (int i = 0; i<sizeof(colors)/sizeof(colors[0]); ++i)
{
cout << colors[i] << endl;
}
}
void printRandomColor()
{
int random_integer = rand() % 7;
cout << random_integer << endl;
}
private:
string colors[7];
};
int main(int argc, const char * argv[]) {
srand( static_cast<unsigned int>(time(0)));
Color colorObject;
colorObject.printRandomColor();
return 0;
}
当我做 rand() % 7
我一直得到 6,但如果我这样做了 rand() % 6
我最终得到了随机数。给了什么?
我调用srand( static_cast<unsigned int>(time(0)));
在我的 main() 中
最佳答案
我注意到问题中显示的代码有相同的行为:
rand() % 7 // always shows 6
rand() % 14 // always shows 6 or 13
rand() % 21 // always shows 6, 13, or 20
这个问题很奇特,似乎涉及一种模式。基于某些人无法重现它的评论,我决定编译代码,在基于 Linux 的机器上使用 gcc,在 macOS 上使用 clang;据我所知,Linux 似乎表现正常,但 macOS 却没有。我什至尝试了完全不同的代码以确保它不是别的东西,但得到了相同的结果。
#include <cstdlib>
#include <iostream>
#include <ctime>
int main()
{
int min = 1;
int max = 7;
std::srand(std::time(0)); // use current time as seed for random generator
// int random_variable = std::rand() % max; // always returns 6
// int random_variable = std::rand() % (max - min) + min; // produces 'predictable' numbers based on the time.
int random_variable = RAND_MAX % std::rand() % (max-min) + min; // also returns predicate results based on the timing, except in reverse.
std::cout << "Random value on [0 " << RAND_MAX << "]: "
<< random_variable << '\n';
}
我能够从 rand()
获得看似随机结果的唯一方法是要做的:
RAND_MAX % std::rand() % (max-min) + min; // predictable based on timing
这个问题很奇怪,可能是 Clang 的一个错误;我不知道这里到底在玩什么。我可能会推荐使用 rand()
以外的东西例如<random>
评论中可能提到的图书馆。
编辑:在向 Apple 报告此错误后,这是回应:
Apple Developer Relations July 27 2017, 11:27 AM
There are no plans to address this based on the following:
std::rand directly uses rand from the C library. rand is known and documented to be broken (and is not going to change since people depend on its specific behavior).
From the man page: RAND(3) BSD Library Functions Manual
NAME rand, rand_r, srand, sranddev -- bad random number generator
DESCRIPTION These interfaces are obsoleted by arc4random(3).
For good pseudorandom numbers in C++, look at from C++11. E.g.: http://en.cppreference.com/w/cpp/numeric/random
基于此信息RAND()
已损坏且无法修复 — 使用替代随机数生成器。
关于c++ - rand()不根据xcode中的模给出随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44742149/