samedi 26 mars 2022

how do i randomly select an element in an array?

So I've been trying to do this for an embarrassingly long time now. First of all here is my (very bad) code:

char firstInfection() {            
     char cities[] = {"aa", "bb", "cc", "dd", "ee", "ff"};            
     srand(time(NULL));            
     int randnum = rand() % 5;            
     char firstCity = cities[randnum];            
     return firstCity; 
}

I didn't include the preprocessor stuff but I'm also using string, math and time (obviously stdio and stdlib too)

Line 2 errors out here, saying: error: too many initializers for ‘char []’ I'm not really sure what's going on here.

I'm having trouble understanding some of the things I need to do. I was told on tutorialspoint that I have to initialize random with line 3: srand(time(NULL)) I'm not sure why lol.

I tried shortening the names of the elements in cities[]

I'm not really sure what else to do try. I'm guessing that the whole thing is completely wrong but I really don't know.




Aucun commentaire:

Enregistrer un commentaire