【问题标题】:printing randome choices from an array从数组中打印随机选择
【发布时间】:2012-12-23 08:32:25
【问题描述】:

我正在研究一个从给定数组中选择随机数并将它们打印到标准输出的函数。这些数字不应重复,选择的数字与数组一起提供给函数。我有一个单独的函数测试文件和一个头文件。一切都编译得很好,但是当我运行程序时,我在 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;
} 

【问题讨论】:

  • 调用这个函数时pickNumbers的参数是什么?

标签: c arrays function loops while-loop


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在您的第一个“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

    【讨论】:

      【解决方案3】:

      也许

      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++) {
      

      【讨论】:

      • 不,这仍然给我同样的挂断,我想我在增加数组时可能会遗漏一些东西
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      相关资源
      最近更新 更多