2016-03-15 121 views
-1

我只是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"}; 

感谢提前!

+2

创建一个索引数组(0-19)并使用rand函数对其值进行洗牌。然后回答和问题不会丢失链接 – nikniknik2016

+2

您应该使用计算器并仔细检查您的问题和答案。 – molbdnilo

+0

您可以使用[std :: shuffle](http://www.cplusplus.com/reference/algorithm/shuffle/)。另外,你似乎在第二行中有错误印记。必须是“9的平方根”而不是“6的平方根”。而42和48也有同样的问题(必须是49和64)。 – Ilya

回答

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; 
} 
1

正如有关问题的评论中提到,你可以从cstdlib使用rand()并限制返回的随机数,使用modulus(%)

srand(time(NULL)); 
index = rand() % array_size; 

然后使用该索引访问数组中的问题。

cout << questionpart[index] << endl; 

编辑:您可能需要使用ctime的函数srand

EDIT2:不重复同样的问题随机化,您可能需要存储已经用于跟踪它的问题或如果你不再需要它,只需从阵列中完全删除它。

了更先进的方法,你可以定义一个对象,将持有的一切(问题,答案,以及状态) 类似:

class Question { 
    string question; 
    string answer; 
    bool wasAsked = false; 
} 

然后创建一个数组出来的(或最好vector为动态数组支持)

Question questions[array_size]; 
+0

嗨,我试过这样说,我没有声明array_size和索引。你知道这是为什么吗?谢谢! –

+1

虽然这可能会不止一次地打印问题 - 我对“洗牌”的理解是,您最多一次询问每个问题,但以随机顺序。 –

+0

@FrerichRaabe这就是我想要的。任何想法我会怎么做,而不是多次打印? –