我应该用1个骰子运行一个enter image description here00的随机掷骰子模拟,在每个掷骰子的末尾,计算并打印结果面值的频率.然后,绘制一个频率与面值的条形图,该条形图由‘*’符号组成,如下所示.生成的图形将接近均匀分布,如下所示: enter image description here个
-程序输出应与上述程序输出在形状上相同. -我只能使用stdio.h,stdlib.h,time.h函数库.
/* 1. */
/* Libraries used for writing this code. */
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
/* Rolling a six-sided dice 10000 times. */
int main()
{
/*Counters for the number of times each face (1-6) is rolled. */
int Times1 = 0;
int Times2 = 0;
int Times3 = 0;
int Times4 = 0;
int Times5 = 0;
int Times6 = 0;
int roll; /* Roll counter for values from 1 to 10000 */
int face; /* One roll of the dice, value between 1 - 6 */
srand( time(NULL) ); /* Changes the result for every run of the code. */
for (roll = 1; roll <= 10000; roll++) { /* Setting loop counter to 10000 */
face = 1 + rand() % 6; /* Random value of dice after a roll, value between 1 - 6 */
switch (face) { /* Switch and case statement for the rolled face value counter. */
case 1:
++Times1;
break;
case 2:
++Times2;
break;
case 3:
++Times3;
break;
case 4:
++Times4;
break;
case 5:
++Times5;
break;
case 6:
++Times6;
break;
}
}
printf("%s%10s\n", "Dice", "Times"); /* Printing command the header for the result table */
/* Printing commands for the each rolled face value. */
printf(" 1%10d\n", Times1);
printf(" 2%10d\n", Times2);
printf(" 3%10d\n", Times3);
printf(" 4%10d\n", Times4);
printf(" 5%10d\n", Times5);
printf(" 6%10d\n\n", Times6);
/* Temporary variables to hold the number of times each face was rolled. */
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int value6 = 0;
/* Copy of the roll counts in temporary variables. */
value1 = Times1;
value2 = Times2;
value3 = Times3;
value4 = Times4;
value5 = Times5;
value6 = Times6;
/* Variables for the number of asterisks printed for each face value. */
int line1 = 0;
int line2 = 0;
int line3 = 0;
int line4 = 0;
int line5 = 0;
int line6 = 0;
printf("1 "); /* Command to print the label for the histogram. */
/* While loop to print asterisks representing the number of times face value 1 was rolled. */
while (line1 < value1) {
printf("* ");
line1 += 150; /* Adjusting the value of each asterisks. */
}
printf("\n");
/* Same loop for the face values 2-6 */
printf("2 ");
while (line2 < value2) {
printf("* ");
line2 += 150;
}
printf("\n");
printf("3 ");
while (line3 < value3) {
printf("* ");
line3 += 150;
}
printf("\n");
printf("4 ");
while (line4 < value4) {
printf("* ");
line4 += 150;
}
printf("\n");
printf("5 ");
while (line5 < value5) {
printf("* ");
line5 += 150;
}
printf("\n");
printf("6 ");
while (line6 < value6) {
printf("* ");
line6 += 150;
}
return 0; /* Indicates successful program termination. */
} /* End of the main code. */