1

I want to randomly choose between 1 and 50 Pokemons, but rand chooses only the 42nd one of the array (Dragonite). How can I make it be random?

#include <stdlib.h>
#include <stdio.h>

int main(){

    char sorteio1[50][11] = {"Bulbasaur","Venusaur","Charmander","Charmeleon","Charizard","Pidgey","Pidgeotto","Pidgeot","Pikachu","Raichu","Clefairy","Vulpix","Ninetales","Meowth","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Abra","Kadabra","Alakazam","Magnemite","Magneton","Onix","Cubone","Marowak","Staryu","Starmie","MrMime","Jynx","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Porygon","Snorlax","Dragonair","Dragonite","Mewtwo","Mew","Chikorita","Sentret","Furret","Hoothoot","Lanturn","Pichu"};
    int i;

    i = rand() %50;

    printf ("%s\n",sorteio1[i]);    

    system ("Pause");
    return 0;
}
Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
  • 4
    This site is in English, perhaps you want [Stack Overflow em Português](http://pt.stackoverflow.com/)? – Some programmer dude Sep 21 '18 at 16:20
  • 3
    I can't tell whether that is Spanish or Portuguese. You might want to post that at https://es.stackoverflow.com/ or https://pt.stackoverflow.com/. – R Sahu Sep 21 '18 at 16:20

1 Answers1

0

You should seed your random number - you can use the current time to give you different inputs.

Check srand documentation.

The example from the documentation:

/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}
Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
  • Is this the only way to get this right? I don't know if I'll be allowed to use time.h – Camila Oliveira Sep 21 '18 at 16:28
  • Time is only used to get you a seed that changes all the time. If you find another way of generating a seed that is different each time you run the program, you can replace this call (maybe asking the user to type a number for the seed)... – Leonardo Alves Machado Sep 21 '18 at 16:33
  • 1
    By the way, this site is in english - I edited your question to be on-topic here. You should accept it before you get too many downvotes or it gets closed – Leonardo Alves Machado Sep 21 '18 at 16:34
  • @LeonardoAlvesMachado Pleae flag/vote to close obvious dupes. This question has been asked many a time. – NathanOliver Sep 21 '18 at 16:36