阵列和整数的误差输出商

问题描述 投票:0回答:1

代码模拟两个滚动死36000倍和输出“萨姆= _;频率= _;百分比= _”。编译代码正确输出一切除了百分比。 “百分比= 0”时,它应输出“(频率[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);
}

}

c arrays tabular
1个回答
1
投票

当你做两个整数之间的分工,其结果也将是一个整数,“精确”结果被截断,以适应一个整数。例子:

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
© www.soinside.com 2019 - 2024. All rights reserved.