提问人:Loading Screen 提问时间:10/8/2023 更新时间:10/8/2023 访问量:49
如何在随机问答生成器循环中标记重复项?
How do I flag duplicates in my random question/answer generator loop?
问:
我正在开发一个应该像琐事测验一样的程序。它从每个字符串列表中随机选择一个问题和答案。但我不确定如何防止它在显示后再次显示相同的问题/答案。我猜我必须标记它,但不知道如何实现它。
以下是问题生成器的片段:
srand(time(0));
questionGenerated = rand() % 6 + 1; // picks a num 1-6 and looks for matching case
switch (questionGenerated) // containing the question and correct answer strings
{
case 1:
cout << question1String;
correctAnswer = answer1String;
break;
// ...and so on with cases 2-6
}
我还做了一个东西,以升序在数字旁边显示答案,所以它可以是一个菜单,你可以从中选择,同时仍然有随机的答案。有同样的问题。
// find out the correct answer int first,
// so incorrect answer int can be compared to it:
correctAnswerInt = rand() % 3 + 1;
while (reroll > 0)
{ // pick the number the incorrect answer will go next to:
incorrectAnswerInt = rand() % 3 + 1;
// determine where it and correct answer will go in the ascending order:
if (incorrectAnswerInt > correctAnswerInt)
{
cout << correctAnswerInt << " " << correctAnswer << "\n";
reroll -= 1;
}
else if (incorrectAnswerInt < correctAnswerInt)
{
cout << incorrectAnswerInt << " " << incorrectAnswer << "\n";
reroll -= 1;
}
// or if it's equal to correct answer int, roll again:
else
reroll += 1;
}
预期输出示例,供参考:
Question 3
1 Incorrect Answer
2 Correct Answer
3 Incorrect Answer
它现在没有按预期工作,但我主要担心标记重复项。比如,连续两次没有得到 2 或“比利时的首都是什么?
我想过添加一个带有布尔值的 if/else,如果为 true,则重新滚动问题。我担心这样的事情会导致无限循环:
while (questionHasBeenDisplayed = true)
{
switch (questionGenerated)
{
case 1:
questionHasBeenDisplayed = true;
if (questionHasBeenDisplayed)
// not sure how to send it back to start of loop from here,
// but imagine some code here that does that
else
cout << question1String;
correctAnswer = answer1String;
// etc.
}
}
我也可以尝试为每个问题添加一个标志,但这似乎有很多变量。
对于我的答案代码,我唯一能想到的就是:
while (reroll > 0)
{
incorrectAnswerInt = rand() % 3 + 1;
if (incorrectAnswerInt == incorrectAnswerInt && incorrectAnswerInt > correctAnswerInt)
// etc...
}
这总是会失败并导致无限循环。
我现在想知道是否有办法检查变量的先前值(从上一个循环开始)并将其与循环中变量的当前值进行比较。这可能只是意味着再次创建另一个变量并重新编写代码。
我想我现在会研究一下,但与此同时,任何建议都是值得赞赏的。谢谢。
答: 暂无答案
下一个:如何在Qt中定期调用函数?
评论
struct QandA { std::string question; std::string answer; bool flag; };
QandA
std::vector<QandA> quiz;