【问题标题】:Random element in an array in CC中数组中的随机元素
【发布时间】:2015-02-08 19:14:20
【问题描述】:

我正在尝试制作一个策划游戏。用户必须猜测随机生成的颜色。 我写了随机方法,但它总是从相同的元素开始,接下来的 3 个是 与第一个元素相同但不同(例如I,o,o,o I,r,r,r)。如何修复我的代码?

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

#define cLength 6

int gen_rand();  
// start of main
int main() {
  int i, rNum;

  // this is the array for the easy mode
  char colours[cLength + 1] = {'r', 'o', 'y', 'g', 'b', 'i', 'v'};
  // this is the randomly generated array
  char rand[3 + 1] = "";
  // this is the guess array that the user will populate
  char guess[3 + 1] = "";

  // for statement to populate the rand array with random elements in the colours array
  rand[0] = colours[gen_rand()]; 
  rand[1] = colours[gen_rand()]; 
  rand[2] = colours[gen_rand()]; 
  rand[3] = colours[gen_rand()]; 

  printf("\n%c", rand[0]);
  printf("\n%c", rand[1]);
  printf("\n%c", rand[2]);
  printf("\n%c", rand[3]);
  // for statement to populate the guess array
  for (i = 0; i < 4; i++) {
    printf("\n Please enter a colour e.g r for Red : ");
    scanf("%c", &guess[i]);
    fflush(stdin);
  }

  printf("%c", guess[2]);
  printf("\n\n\n");
  system("pause");
}

int gen_rand() { // returns random number in range of 0 to 99
  int r = rand() % 6;
  srand(time(NULL));
  return r;
}

【问题讨论】:

  • gen_rand “返回 0 到 99 范围内的随机数”
  • 是的 99 应该是 6 :p
  • 也可以观看这个视频...channel9.msdn.com/Events/GoingNative/2013/…
  • 其实99和6应该是7……他的数组有7种颜色。当然,将 srand() 放在 main() 中。

标签: c arrays random methods


【解决方案1】:

您对srand() 的调用打错了,它需要在您使用随机数生成器之前进行,以影响它。

另外,不要使用模数来计算随机数,这是一种糟糕且损坏的方法,通常会保证它们不是均匀分布的。

请参阅this question,了解有关如何生成更多高质量随机整数的一系列建议。

【讨论】:

  • 我认为浮点转换可能在大多数情况下都有效,但根据您的范围和域,您最终可能会出现“洞”或“团块”,这也会弄乱分布(也许不仅使用16 位 rand()),我认为丢弃超出范围的数字会更安全...即使这意味着您平均每个使用的数字都会调用 50 次 rand()..
  • 你能分享一个例子吗?
  • @GradyPlayer 是的,我退缩了一点,而是提供了一个链接。
  • 在这里选择一个带有 %7 的项目就可以了。你不是在模拟数十亿手牌,在这种情况下,一个小的统计偏差是可以测量的,所以不要担心。但是你确实需要移动 srand()。
【解决方案2】:

致电srand一次。每次调用gen_rand 函数时,都会调用srand,但您只需播种一次即可。所以把它移到main的开头。


 rand[0] = colours[gen_rand()]; 
 rand[1] = colours[gen_rand()]; 
 rand[2] = colours[gen_rand()]; 
 rand[3] = colours[gen_rand()]; 

printf("\n%c", rand[0]);
printf("\n%c", rand[1]);
printf("\n%c", rand[2]);
printf("\n%c", rand[3]);

可以像使用循环一样缩短

for(i=0; i<4; i++)

您的代码中有哪些。

【讨论】:

  • 当你说调用一次。你的意思是放“srand(time(NULL));”在 get_rand() 函数之外,因为如果是这样,我会得到一堆错误。
  • 就在int main(){之后,即main的开头
  • 我遇到了很多错误。大多数是下标需要数组或指针类型错误。
  • @Plisken,您的代码还有其他问题。你可以提出一个新的问题。
【解决方案3】:

您必须调用srand()调用rand(),如果您打算使用rand()为伪随机数生成器之前播种。

【讨论】:

    【解决方案4】:

    请记住,随机函数使用数学函数会产生随机性的错觉。 如果用相同的“种子”初始化,它们中的大多数会给出相同的数字序列。 所以记得把一个变化的值作为种子,比如毫秒或类似的东西。

    由于这很可能是一个学习C的项目,你可以尝试编写自己的随机方法(不容易!!!!),不要忘记你可以随时查看C标准的实际代码函数 (^^) 以获得灵感。这是从“有些好”的代码中学习的好方法。

    (我知道,这只是一般性的输入。但是有用吗..?)

    【讨论】:

      猜你喜欢
      • 2013-06-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 2013-11-14
      • 2016-05-15
      • 1970-01-01
      • 2014-06-19
      相关资源
      最近更新 更多