如何随机排列数组问题
How to shuffle array questions?
我只是C++新手。当我出手时,有人可以帮我随机化这个问题吗?有没有办法随机化这个?
我有这个代码。有人可以告诉我如何随机化这些吗?
string questionpart[20]={"What is the square root of 4?",
"What is the square root of 6?",
"What is the square root of 16?",
"What is the square root of 25?",
"What is the square root of 36?",
"What is the square root of 42?",
"What is the square root of 48?",
"What is the square root of 81?",
"What is the square root of 100?",
"What is the square root of 121?",
"What is the square root of 144?",
"What is the square root of 169?",
"What is the square root of 196?",
"What is the square root of 225?",
"What is the square root of 256?",
"What is the square root of 289?",
"What is the square root of 324?",
"What is the square root of 361?",
"What is the square root of 400?",
"What is the square root of 1?",
};
string partans[20]={"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"1"};
提前感谢!
您可以创建一个索引向量并为其使用std::shuffle
您也可以使用半手动洗牌。例:
srand(time(NULL));
rand();
unsigned indexes[cnt];
unsigned fact = 0;
while(fact < cnt)
{
const unsigned r = rand() % cnt;
bool was = false;
for(unsigned i = 0; i < fact; ++i)
{
if(indexes[i] == r) {
was = true;
break;
}
}
if(!was)
{
indexes[fact] = r;
++fact;
}
}
for(unsigned i = 0; i < cnt; ++i)
{
const unsigned j = indexes[i];
cout << "Q: " << questions[j] << "; A: " << answers[j] << endl;
}
正如在对问题的评论中提到的,您可以使用 cstdlib 中的 rand() 并限制返回的随机数,请使用模数 (%)。
srand(time(NULL));
index = rand() % array_size;
然后使用该索引访问数组中的问题。
cout << questionpart[index] << endl;
编辑:您可能需要使用ctime作为srand
EDIT2:要在不重复相同问题的情况下随机化,您可能需要存储已经用于跟踪它的问题,或者如果您不再需要它,只需将其从数组中完全删除。
对于更高级的方法,您可以定义一个将保存所有内容(问题、答案和状态)的对象像这样:
class Question {
string question;
string answer;
bool wasAsked = false;
}
然后从中创建一个数组(或者最好是动态数组支持的矢量)
Question questions[array_size];
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输入std::数组时出现问题
- 类对象数组的问题会导致崩溃
- 传递二维数组时出现问题
- 从 C++ 中的函数返回数组地址问题
- 使用数组时出现问题
- 打印问题.我在数组中打印值时遇到一些问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 将字节数组转换为带有字节序问题的指针
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 编写 cin.get() 以接收字符数组时出现问题
- 在 C++ Consol 中的数组中执行用户命令时出现问题
- 存储另一个函数返回的布尔数组时遇到问题
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 运行时C++数组初始化问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组