从C ++中的数组中选择一个随机元素

时间:2018-09-21 16:17:02

标签: c++ arrays elementor

我想在1到50个神奇宝贝之间随机选择,但是rand仅选择数组中的第42个(龙猫)。如何使其随机?

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

1 个答案:

答案 0 :(得分:0)

您应该为您的随机数设定种子-您可以使用当前时间为您提供不同的输入。

选中srand 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;
}