我写了一个小的掷骰子程序,它将打印出输入多少掷骰子的结果。我想要计算每个数字出现的次数,所以我想我应该将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;
}
发布于 2013-04-25 15:47:11
#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-25 15:47:13
只需将其放入数组即可
for (roll = 0; roll < count; roll++)
{
myArray[roll] = rand() % 6 + 1;
printf("%d\n", myArray[roll] );
}
发布于 2013-04-25 15:59:36
如果您想要跟踪每个结果的出现次数,您甚至不需要保存每个掷骰子。
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以获得实际的滚动)。即。结果是“1”的出现次数。
https://stackoverflow.com/questions/16219164
复制相似问题