0

我写了一个小骰子滚动程序,无论输入多少骰子,它都会打印出结果。我想计算每个数字出现了多少,所以我想我会将 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;
      }
4

3 回答 3

2
    #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;
      }
于 2013-04-25T15:47:10.757 回答
0

just put it into the array

for (roll = 0; roll < count; roll++)
{
    myArray[roll] = rand() % 6 + 1;
    printf("%d\n", myArray[roll] );
}
于 2013-04-25T15:47:13.140 回答
0

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

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”的出现次数。

于 2013-04-25T15:59:36.357 回答