我相信这与我使用roll_die有关。如果我只是在体内使用rand()%6 + 1而不是roll_die,那么它可以工作,但是我想使用该函数。此外,是否有任何方法可以使用更少的行来打印结果以使代码更短?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int roll_die() {
return 1 + rand() % 6;
}
int main()
{
srand((unsigned) time(0));
int roll_die;
int first_die_roll, second_die_roll, total;
int roll_result[13] = {0};
int count = 36000;
while(count--) {
first_die_roll = roll_die;
second_die_roll = roll_die;
total = first_die_roll + second_die_roll;
roll_result[total]++;
}
printf("Computed die rolling frequencies for 36,000 rolls:\n");
printf("Sum = 2; Frequency = %d ; Percentage = %f%c\n", roll_result[2], (float)roll_result[2]/36000 * 100, '%');
printf("Sum = 3; Frequency = %d ; Percentage = %f%c\n", roll_result[3], (float)roll_result[3]/36000 * 100, '%');
printf("Sum = 4; Frequency = %d ; Percentage = %f%c\n", roll_result[4], (float)roll_result[4]/36000 * 100, '%');
printf("Sum = 5; Frequency = %d ; Percentage = %f%c\n", roll_result[5], (float)roll_result[5]/36000 * 100, '%');
printf("Sum = 6; Frequency = %d ; Percentage = %f%c\n", roll_result[6], (float)roll_result[6]/36000 * 100, '%');
printf("Sum = 7; Frequency = %d ; Percentage = %f%c\n", roll_result[7], (float)roll_result[7]/36000 * 100, '%');
printf("Sum = 8; Frequency = %d ; Percentage = %f%c\n", roll_result[8], (float)roll_result[8]/36000 * 100, '%');
printf("Sum = 9; Frequency = %d ; Percentage = %f%c\n", roll_result[9], (float)roll_result[9]/36000 * 100, '%');
printf("Sum = 10; Frequency = %d ; Percentage = %f%c\n", roll_result[10], (float)roll_result[10]/36000 * 100, '%');
printf("Sum = 11; Frequency = %d ; Percentage = %f%c\n", roll_result[11], (float)roll_result[11]/36000 * 100, '%');
printf("Sum = 12; Frequency = %d ; Percentage = %f%c\n", roll_result[12], (float)roll_result[12]/36000 * 100, '%');
return 0;
}
Your declaration
int roll_die;
insidemain
declaresroll_die
as a localint
variable, and hides the function with the same name. Thus, when you later have a line such as this:You are assigning to
first_die_roll
the value of the unitialized local variable.Fix: First, remove the declaration of the local variable; then, to invoke the
roll_die
function, you will need to add parentheses to the name, wherever you need it:随时要求进一步的澄清和/或解释。