【问题标题】:Choose a random element from an array in C++ [duplicate]从C ++中的数组中选择一个随机元素[重复]
【发布时间】:2019-02-26 02:16:48
【问题描述】:

我想在 1 到 50 个口袋妖怪之间随机选择,但rand 只选择数组中的第 42 个(Dragonite)。我怎样才能让它变得随机?

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

【问题讨论】:

标签: c++ arrays elementor


【解决方案1】:

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

检查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;
}

【讨论】:

  • 这是解决这个问题的唯一方法吗?我不知道我是否可以使用 time.h
  • 时间只用来给你一个时时刻刻变化的种子。如果您发现每次运行程序时生成不同种子的另一种方式,您可以替换此调用(可能要求用户为种子输入一个数字)...
  • 顺便说一下,这个网站是英文的 - 我编辑了你的问题,以便在这里成为主题。您应该在收到太多反对票或关闭之前接受它
  • @LeonardoAlvesMachado Pleae 标志/投票关闭明显的欺骗。这个问题已经被问过很多次了。
猜你喜欢
  • 2012-01-23
  • 2013-03-03
  • 2014-07-23
  • 1970-01-01
  • 2023-01-11
  • 1970-01-01
  • 2015-04-12
相关资源
最近更新 更多