将rand()的输出放入数组中

时间:2013-04-25 15:43:05

标签: c arrays random

我写了一个小骰子滚动程序,打印出输入的许多骰子卷的结果。我想计算每个数字的出现次数,所以我想我会把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;
      }

3 个答案:

答案 0 :(得分: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;
      }

答案 1 :(得分:0)

将它放入数组

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

答案 2 :(得分: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来获得实际的掷骰)。即。 result [0]是'1'的出现次数。