我正在使用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
来获取章节和主题值。他们不会为此烦恼。
这里的主要问题是,每次编写代码时,编译执行时,每次都会提供相同的问题。例如,对于当前的随机逻辑,我得到了这个问题:
人们可以在这个千年中改善自己并取消这个标签吗?
每当我改变逻辑时,我得到一个新的结果,但在每个条件下都是相似的(该特定逻辑的代码执行)!我想要的是获取随机问题,每次执行代码时,我应该更改生成此随机数的位置吗?或者我在其他地方做错了什么?
答案 0 :(得分:5)
您应该使用srand
函数使用随机种子值初始化随机数生成器来更改rand()
函数的此行为。
您可以使用类似srand (time(NULL));
的内容来使用不同的种子初始化随机生成器。
答案 1 :(得分:2)
您没有播种随机数生成器,因此每次运行该程序时,您将获得相同的随机数序列。在程序开始时使用srand一次。
答案 2 :(得分:1)
您需要使用标头std::srand
中声明的函数<cstdlib>
来设置随机序列。
例如
class English {
public:
English() { if ( !init ) std::srand( unsigned( std::time( 0 ) ) ); init = true; }
string get_questions (int number) const {
if (number == 1) {
// Chapter 1
string questions[10] = { /*...*/ };
string result = questions[rand() % 10] + "\n";
return result;
}
}
private:
static bool init;
};
bool English::init = false;
考虑到我在功能get_questions
答案 3 :(得分:1)
如果您使用的是兼容C ++ 11的编译器,更好的解决方案是使用<random>
库:
// initialize your string array
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,9);
int index = distribution(generator);
return questions[index];