输出数组和整数的商时出错

Error outputting quotient of array and integer

代码模拟两个骰子滚动36000次,输出"Sum = _; Frequency = _; Percentage = _"。编译后的代码正确输出除百分比以外的所有内容。 "Percentage = 0" 什么时候应该输出 "(frequency[calcCount] /36000) * 100" 的商 这是数据类型冲突吗?如何正确输出商数?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SUM_SIZE 36000
#define FREQUENCY_SIZE 13

int main(void){
    int rollCount; // counter to loop through 36000 rolls of dice & sums
    int calcCount; //counter to loop through frequencies 1-12 of sum calculation

//initialize frequency counters to 0
int frequency[FREQUENCY_SIZE] = {0};

//calculation array
int calculation[SUM_SIZE];

//seed
srand((unsigned)(time(NULL)));

for (rollCount = 1; rollCount <= SUM_SIZE; rollCount++){
    //rolling first die
    int face1 = (1 + ( rand() % 6));
    //rolling second die
    int face2 = (1 + ( rand() % 6));
    int sum = face1 + face2;
    //initializing array elements
    calculation[rollCount] = sum;
    //for each roll, select value of an element of array calculation
    //and use that value as subscript in array frequency to determine
    //element to increment (which in this case is the sum frequency)
    ++frequency[calculation[rollCount]];
}

//displaying results
for (calcCount = 2; calcCount < FREQUENCY_SIZE; calcCount++){
    //calculating percentage
    int percentage = (frequency[calcCount] /36000) * 100;
    printf("Sum = %d; Frequency = %d; Percentage = %d \n", calcCount, frequency[calcCount], percentage);
}

}

当您在两个整数之间进行除法时,结果也将是一个整数,并且 "exact" 结果会被截断以适合一个整数。示例:

3/2 -> 1
10/3 -> 3
5/10 -> 0

当你这样做时

int percentage = (frequency[calcCount] /36000) * 100;

先计算frequency[calcCount] /36000部分。它是两个 int 之间的除法,结果为零,因为 frequency[calcCount] 小于 36000。因此乘以 100 仍为零。

而是先做乘法——比如:

int percentage = (100 * frequency[calcCount]) /36000;

另一种方法是使用浮点数,如:

double percentage = (frequency[calcCount] /36000.0) * 100;
                                                ^^^
                               Notice the .0 to make 36000 a double

但是您需要更改打印以使用 %f

double percentage = (frequency[calcCount] / 36000.0) * 100;
printf("Sum = %d; Frequency = %d; Percentage = %.2f \n", calcCount, frequency[calcCount], percentage);
                                                ^^^
                                        Notice this to print the double