【问题标题】:Putting output from rand() into an array将 rand() 的输出放入数组
【发布时间】:2013-04-26 01:13:06
【问题描述】:

我编写了一个小骰子滚动程序,无论输入多少骰子,它都会打印出结果。我想计算每个数字出现了多少,所以我想我会将 rand() 函数的输出放入一个数组中,然后在数组中搜索不同的值。我不知道如何将数字放入未手动输入的数组中。

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

    int main(void)
    {
        int count; 
        int roll;  

        srand(time(NULL));

       printf("How many dice are being rolled?\n");
       scanf("%d", &count);

       printf("\nDice Rolls\n");
       for (roll = 0; roll < count; roll++)
       {
         printf("%d\n", rand() % 6 + 1);
       }
       return 0;
      }

【问题讨论】:

  • 哦,天哪! 新用户。没有&lt;stdio.H&gt;。我想你的意思是&lt;stdio.h&gt;。你在看哪本书?
  • 是的,这是一个错字。我有 C 绝对初学者指南,Greg Perry 的第二版和 C Primer Plus,Stephen Prata 的第五版。

标签: c arrays random


【解决方案1】:
    #include <stdio.H>
    #include <stdlib.h>
    #include <time.h>

    int main(void)
    {
        int  count; 
        int  roll;  
        int* history;

        srand(time(NULL));

        printf("How many dice are being rolled?\n");
        scanf("%d", &count);

        history = malloc( sizeof(int) * count );

        if( !history )
        {
            printf( "cannot handle that many dice!\n" );
            exit( -1 );
        }

        printf("\nDice Rolls\n");
        for (roll = 0; roll < count; roll++)
        {
          history[roll] = rand() % 6 + 1;
          printf("%d\n", history[roll]);
        }

        // do something interesting with the history here

        free( history );
        return 0;
      }

【讨论】:

  • 如果您添加检查分配失败,为什么不添加检查错误scanf
  • 因为我不是要教他怎么使用scanf,而是教他如何正确分配和使用动态数组? ~微笑~
【解决方案2】:

直接放入数组中

for (roll = 0; roll < count; roll++)
{
    myArray[roll] = rand() % 6 + 1;
    printf("%d\n", myArray[roll] );
}

【讨论】:

  • 请记住,您的解决方案没有考虑到用户正在输入可变数量的骰子来滚动,而不是特别是三个骰子。
【解决方案3】:

如果您想跟踪每个结果的出现次数,您甚至不需要保存每个掷骰子。

int result[6] = {} ; // Initialize array of 6 int elements
int current = 0; // holds current random number
for (roll = 0; roll < count
{
     current = rand() % 6;
     result[current]++; // adds one to result[n] of the current random number
     printf("%d\n", current+1);
}

之后,您将有一个 0-5 数组(结果),每个元素包含每次出现的次数(您需要添加元素编号 + 1 才能获得实际滚动)。 IE。 result[0] 是 '1' 的出现次数。

【讨论】:

  • 欢迎来到 StackOverflow,@Jon。
  • 为什么,谢谢。是的,这是正确的 twalberg,所以也感谢您的更正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 2011-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多