roll
和exp
最初都是在main()
中声明的大小为13的一维数组。
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
typedef struct {
int roll;
int exp;
} Roll;
int main ( void )
{
char quit;
printf("\n A simulation of dice rolls to determine roll frequencey:\n");
do {
FILE *fp;
int input;
int num1, num2, sum, total = 0,i;
Roll tosses[13] = { {0, 0}, {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5},
{0, 6}, {0, 5}, {0, 4}, {0, 3}, {0, 2}, {0, 1} };
// ALGORITHM 2: Prompt user for number of rolls and store input.
printf("\n Please enter number of rolls: ");
scanf(" %d", &input);
// ALGORITHM 3: Calculate roll frequency.
for (i = 0; i < input ; i++)
{
sum=0;
num1=1+rand()%6;
num2=1+rand()%6;
sum=num1+num2;
tosses[sum].roll++;
}
for (i = 0; i < 13; i++)
{
total+=tosses[i].roll;
// ALGORITHM 4: Display results.
printf("\n\n");
printf(" Roll: Expected(%%): Session(%%):\n");
for (i = 2; i <= 12; i++)
{
printf(" %2d %9f%% %9f%% (%d / %d)\n", i,
100.0*tosses[i].exp/36, 100.0*tosses[i].roll/input, tosses[i].roll, input);
}
fp = fopen("results.dat", "w");
if (fp == NULL) {
printf("I couldn't open results.dat for writing.\n");
exit(0);
}
fprintf(fp,"\n Roll: Expected(%%): Session(%%):\n");
for (i = 2; i <= 12; i++)
fprintf(fp, "%2d %9f%% %9f%% (%d / %d)\n", i,
100.0*tosses[i].exp/36, 100.0*tosses[i].roll/input, tosses[i].roll, input);
// ALGORITHM 5: Prompt user to roll again or quit.
printf("\n Would you like to run simulation again? (Type: Y / N ): ");
scanf(" %c", &quit);
} while (quit == 'y' || quit == 'Y');
return(0);
}
答案 0 :(得分:2)
没有令人信服的理由将并行数组更改为结构,但这是一种方式:
int ROLL[13]={0};
int EXP[13] ={0,0,1,2,3,4,5,6,5,4,3,2,1};
要
struct {
int roll;
int exp;
} tosses [13] = {
{0, 0}, {0, 0}, {0, 1}, {0, 2}, {0, 3}, {0, 4}, {0, 5},
{0, 6}, {0, 5}, {0, 4}, {0, 3}, {0, 2}, {0, 1}
}
所以,而不是ROLL[sum]++
,它将是
++tosses[sum].roll;