2016-03-15 126 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這就是我想要的。任何想法我會怎麼做,而不是多次打印? –