代码模拟两个模具的滚动36000次,并输出“和= _;频率= _;百分比= _”。编译后的代码可以正确输出除百分比以外的所有内容。当应输出“(frequency [calcCount] / 36000)* 100”的商时为“百分比= 0”,这是数据类型冲突吗?如何正确输出商?
#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);
}
}
答案 0 :(得分:1)
当您在两个整数之间进行除法时,结果也将是整数,并且“精确”结果将被截断以适合整数。例子:
[firefox/remote.js][debug] Received message from client: {"from":"root","type":"tabListChanged"}
[firefox/index.js][debug] Firefox stderr: JavaScript error: moz-extension://c3e66db6-d90b-4c3e-86c1-8346247f5cdb/main.js, line 30: TypeError: browser.runtime.connectNative is not a function
以及您做什么时
3/2 -> 1
10/3 -> 3
5/10 -> 0
部分int percentage = (frequency[calcCount] /36000) * 100;
首先被计算。它是两个frequency[calcCount] /36000
之间的除法,由于int
小于frequency[calcCount]
,因此结果为零。因此,乘以100仍为零。
相反,首先要做乘法-
36000
另一种替代方法是使用浮点,如:
int percentage = (100 * frequency[calcCount]) /36000;
但是您需要将打印更改为使用%f
double percentage = (frequency[calcCount] /36000.0) * 100;
^^^
Notice the .0 to make 36000 a double