【问题标题】:Error outputting quotient of array and integer输出数组和整数的商时出错
【发布时间】:2019-02-03 07:47:33
【问题描述】:

代码模拟两个骰子滚动 36000 次并输出“总和 = _;频率 = _;百分比 = _”。编译后的代码会正确输出除百分比之外的所有内容。 “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);
}

}

【问题讨论】:

    标签: c arrays tabular


    【解决方案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
    

    【讨论】:

    • 感谢您详细说明!绝对感谢对细节的额外关注!
    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多