0

我正在研究一个从给定数组中选择随机数并将它们打印到标准输出的函数。这些数字不应重复,选择的数字与数组一起提供给函数。我有一个单独的函数测试文件和一个头文件。一切都编译得很好,但是当我运行程序时,我在 pickNumbers 函数中挂断,没有打印任何内容,我什至不知道是否选择了任何内容。

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

//program that picks random numbers from the given array
int alreadyPicked(int choices[], int choice);

void pickNumbers(int myArray[],int max)
{
  // delcare/initilize variables
  int i;
  int choices[max];
  int length = sizeof(myArray)/sizeof(myArray[0]);
  // seed rand
  srand(time(NULL));

  // pick a random choice until that given number of choices is reached
  // to make sure non repeat run against alreadyPicked function
  for (i=0; i <= max; i++) {
    do{
      choices[i] = (rand() % max);
    }while (alreadyPicked(choices, choices[i]) == TRUE);
  }

  for (i=0; i <= max; i++) {
     printf("%d", myArray[choices[i]]);
  }
  printf("\n"); 
}

int alreadyPicked(int choices[], int choice)
{
  int i;
  int answer = FALSE;
  for (i=0; i <= (sizeof(choices)/sizeof(choices[0])); i++) {
    if(choices[i] == choice)
      answer = TRUE;
  }
  return answer;
} 
4

3 回答 3

1

也许

for (i=0; i <= max; i++) {

一定是:

for (i=0; i < max; i++) {

 for (i=0; i <= (sizeof(choices)/sizeof(choices[0])); i++) {

一定是:

 for (i=0; i < (sizeof(choices)/sizeof(choices[0])); i++) {
于 2013-01-09T10:14:02.277 回答
0

在您的第一个“for”循环中,您有一个嵌套的 while/do。你在你的for循环中增加“i”,而不是你应该在while/do中增加变量,否则它将永远挂起执行这样的循环,因为“i”永远不会增加。

代替:

for (i=0; i <= max; i++) {

经过:

for (i=0; i < max;) {

并替换:

 choices[i] = (rand() % max);

经过:

 choices[i++] = (rand() % max);

这样,您可以确保“i”正在递增。此外,您的构造“i<=max”也不正确,因为您从 0 开始,使用 David RF 所做的方式。

于 2013-01-09T22:47:31.157 回答
0

除了前面提到的错误循环测试之外,死循环的原因是alreadyPicked()你将新的选择索引与 中的每个选择索引进行比较choices[],包括未初始化的和新的本身;因此,alreadyPicked()总是返回 TRUE。我建议改为调用alreadyPicked()to

alreadyPicked(choices, i)

及其实施

int alreadyPicked(int choices[], int choice)
{
  for (int i = 0; i < choice; i++)
    if (choices[i] == choices[choice])
      return TRUE;
  return FALSE;
}
于 2014-05-13T06:45:06.770 回答