【发布时间】:2014-04-02 16:46:11
【问题描述】:
我正在使用 C++ 为随机问题创建应用程序。但我认为这行不通(由于我的逻辑不好)。我正在尝试的是:
class English {
public:
string get_questions (int number) {
if (number == 1) {
// Chapter 1
string questions[10] = {
"In what way is man considere to be a lower species when compared to animals, in general?",
"What specific triats of character make man the lowest animal in Mark Twain's views?",
"What aspects of human nature are pointed when man is compared with the anaconda, bees, roosters, cats.",
"What specific traits of character make man the lowest animal in Mark Twain's views?",
"Discuss the Importance of the experiments conducted by the Mark Twain.",
"Can people improve themselves and remove this label in thismillennium?",
"What are the traits due to which man cannot claim to have reached the meanest of the Higher Animals?",
"\"The damned Human Race\" was written in 1900, is it valid today?",
"Do you think Mark Twain was accurate while comparing Human nature to that of the birds, insects and other animals?",
"Why did Mark Twain rejected Darwin's theory, what were his conclusions in this regard?"
};
string result = questions[rand() % 9 + 0] + "\n";
return result;
}
}
};
我使用的代码是这样的:
cout << English().get_questions(chapter);
虽然我有更多的行,但它们只是简单的cout 和cin 来获取章节和主题值。他们不会为此烦恼。
这里的主要问题是每次我写完代码,当我编译和执行它时,每次都会提供相同的问题作为结果。例如,对于当前的随机逻辑,我得到这个问题:
人们能否在这个千年里提高自己并去掉这个标签?
每当我更改逻辑时,我都会得到一个新结果,但在每种情况下都相似(该特定逻辑的代码执行)!我想要的是在哪里得到一个随机问题,每次执行代码时,我应该更改生成这个随机数的位置吗?还是我在其他地方做错了?
【问题讨论】:
-
一些 cmets:C 随机数设施非常差:“标准”种子是一个时间值 (
time(NULL)),只有 1 秒的精度,并且不返回与srand()期望相同的类型(因此它失去了精度和可变性)。后来,rand()不能保证产生均匀分布(不),但即使在这种情况下,你使用模运算符打破这种均匀性。 -
所以(我知道情况并非如此,您所公开的内容似乎是一个示例练习)如果您的随机数(您的 PRNG)的质量是一个问题,请考虑 不要使用 C 库,搜索质量好的 PRNG C++ 库。另外,请注意,自 C++11 以来,标准库附带了 random library,它比 C 等效项好 faaaaaaaaaaaaaar。