Java平均计算

时间:2014-10-15 12:50:11

标签: java math

当我在java中运行以下代码时,它没有给出正确的平均结果,它应该是97.5。任何人都可以帮助我。

//class
public class NumericTypes {
    public static void main (String [] args) {
        final int NUMBER = 2 ; // number of scores
        final int SCORE1 = 100; // first test score
        final int SCORE2 = 95; // second test score
        final int BOILING_IN_F = 212; // freezing temperature
        int fToC; // temperature in Celsius
        double average; // arithmetic average
        String output; // line of output to print out

        // Find an arithmetic average
        average = (SCORE1 + SCORE2) / NUMBER;
        output = SCORE1 + " and " + SCORE2 + " have an average of " + average;
        System.out.println(output);

        // Convert Fahrenheit temperatures to Celsius
        fToC = (BOILING_IN_F - 32) * 5/9;
        output = BOILING_IN_F + " in Fahrenheit is " + fToC + " in Celsius.";
        System.out.println(output);
        System.out.println(); // to leave a blank line 
    }
}

2 个答案:

答案 0 :(得分:4)

您正在执行整数数学运算,将其中一个值投射到double,您将获得正确的结果。

average = ((double)(SCORE1 + SCORE2)) / NUMBER;

答案 1 :(得分:2)

尝试更改此

final int NUMBER = 2 ;

final double NUMBER = 2 ;