2016-03-29 38 views
0

我上創建將 1.隨機化選擇題回答 2.顯示來自a)的b)中c)中d)顯示2個重複陣列,一個用於環路

我的選擇的測試的仿真工作有兩個代碼分開完成,但我可以使用for循環去顯示這個?這是做這件事的最好方法嗎?所有的幫助表示感謝,謝謝!對於部分2

#include <iostream> 
#include <ctime> 
#include <cstdlib> 
using namespace std; 

int main(){ 
const int TEST_SIZE = 13; 
srand(time(0)); 
string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" }; 

for (int i = 0; i < TEST_SIZE; i++){ 
    //generate random index number (0,1,2,3,4,5...) 
    int index = rand() % FACE_SIZE; 

    //swap animals[i] with animals[index] 
    string temp = animals[i]; 
    animals[i] = animals[index]; 
    animals[index] = temp; 

} 
//loop through array and print values 
for (int i = 0; i < 7; i++){ 
    cout << animals[i] << " "; 
} 

} 

//單獨的代碼:從AG選擇

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
const int CHOICE_SIZE = 7; 
string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" }; 
for (int i = 0; i < CHOICE_SIZE; i++) { 
cout << choices[i] << " "; 
} 
} 

回答

0

你既可以在陣列和迭代時停止越小結束

#include <iostream> 
#include <ctime> 
#include <cstdlib> 
using namespace std; 

int main(){ 
    const int TEST_SIZE = 13; 
    srand(time(0)); 
    string animals[TEST_SIZE] = {"dog","cat","fish","elephant","rhinoceros","cheetah","tiger","lion","zebra","giraffes","alligators","sloths","kangaroos" }; 

    for (int i = 0; i < TEST_SIZE; i++){ 
     //generate random index number (0,1,2,3,4,5...) 
     int index = rand() % FACE_SIZE; // maybe here should be TEST_SIZE? 

     //swap animals[i] with animals[index] 
     string temp = animals[i]; 
     animals[i] = animals[index]; 
     animals[index] = temp; 

    } 
    //loop through array and print values 
    for (int i = 0; i < 7; i++){ 
     cout << animals[i] << " "; 
    } 

    const int CHOICE_SIZE = 7; 
    string choices[] = { "a)", "b)","c)","d)","e)","f)","g)" }; 
    for (int i = 0; i < CHOICE_SIZE && i < TEST_SIZE; i++) { 
     cout << choices[i] << " " << animals[i] << ", "; 
    } 
} 

此外,考慮到,如果你想要使用固定大小的數組,可以使用std :: array:

#include <array> 
std::array<string, TEST_SIZE> animals = {...}; 

而對於洗牌,你可以使用'算法'頭中的std :: shuffle。