c - C中数组中的随机元素

标签 c arrays random methods

我正在尝试制作一款策划游戏。用户必须猜测随机生成的颜色。 我写了 random 方法,但它一直以相同的元素开始,接下来的 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;
}

最佳答案

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

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

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

关于c - C中数组中的随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27403618/

相关文章:

c++ - 使用 fscanf 时将宽度作为变量

c - 使用 setitimer() 和 ITIMER_VIRTUAL 时,是什么导致虚拟运行时间变慢?

c - C 结构中未声明的函数

javascript - 如何过滤对象数组但更改顺序

algorithm - 将随机范围从 1–5 扩展到 1–7

c - N个按概率随机选择

c - 如何在没有makefile的情况下链接不同目录中的对象?

c - 在内联汇编器中使用寄存器

c - 如何在C中逐行读取由制表符分隔的双数据组成的10 GB txt文件

c - 唯一的随机数