简体   繁体   中英

My program does not output the right decimal numbers of an arithmetic average. How can I fix it?

I need to display the correct arithmetic average of a series of integers entered by the user. If the user enters 6, 9, 7, and 4, the average should be 6.5 but instead displays 6.0. Why does that happen? I used an ArrayList to store all the integers.

import java.util.Scanner;
import java.util.*;
import java.util.Collections;

public class QuizScoreStatistics
{
    public static void main(String[] args) {
        List<Integer> Scores = new ArrayList<Integer>();

        Scanner input = new Scanner(System.in);
        int i = 0;
        int a = 0;

        while(a != 99) {
            System.out.println("Enter scores");
            a = input.nextInt();
            if(a != 99) {
                if ( a > 10 || a < 0) {
                    System.out.println("Score must be between 10 and 0");
            }
            else {
                Scores.add(a);
            }

            i++;
        } 
    }
        int max = Collections.max(Scores);

        int min = Collections.min(Scores);

        int sum = 0;

        double averg = 0;

        for( i = 0; i <= Scores.size() - 1; i++) {
             sum += Scores.get(i);
        }
        averg = sum / Scores.size();

        System.out.println("Scores entered " + i);

        System.out.println("Highest score " + max);

        System.out.println("Lowest score "+ min);

        System.out.println("Average: "+ averg);
    }
}

I won't try to give away the entire question I think you could probably answer that yourself given a nudge in the right direction.

You correctly identified that your averg is a double because your answer could come out to something like 6.7 or 2.3 or whatever. Thats a correct assumption to make, However during your "arithmetic process" you are using integers to do the division. which will come out as an integer, I will repeat the actual DIVISION is happening with two integers? can you see where the bug is coming from?

If you need more of a push to see the exact remedy of this solution I would point you here https://programming.guide/java/wrong-results-for-division.html

Try averg = (1.0 *sum) / Scores.size();
because int/int => int but double/int=>double

Ok, this is how the operator "/" works.

int / int => int
int / float => float
float / int => float

Since you are doing an int division (int/int), the result will be an int, losing decimal information. If you want your division to be float or double, you have two options, either you declare the sum as double or you can just cast the division, so it becomes a double division instead of an int division.

averg = (double) sum / Scores.size();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM