2016-03-29 6 views
0

I auf die Schaffung einer Simulation eines Test arbeite das wird 1. Randomisieren multiple choice 2. Anzeige die Auswahl von a) b) c) d)angezeigte 2 iteriert Arrays in einer Schleife für

I antwortet Habe beide Codes getrennt gemacht aber kann ich for-loop verwenden, um das anzuzeigen? Ist dies der beste Weg, dies zu tun? Alle Hilfe ist dankbar, danke!

#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] << " "; 
} 

} 

// separater Code für Teil 2: Auswahl von 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] << " "; 
} 
} 

Antwort

0

Sie können beide Arrays iterieren und stoppen, wenn kleineren Willen endet

#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] << ", "; 
    } 
} 

Bedenken Sie auch, dass, wenn Sie Wollen Sie ein Array fester Größe verwenden, können Sie std :: array verwenden:

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

Und zum Mischen können Sie std :: shuffle aus 'Algorithmus' Header verwenden.

Verwandte Themen