简体   繁体   中英

Why am I not getting the right average in my java code?

So I am working on an assignment and pretty much its working with methods and returning. My code so far is supposed to print the numbers in an array then it takes those numbers and averages them. I have to use the methods I am given in the exact format they are given but I am not sure why the average is coming out wrong. It is printing 521674.2 as the average which is clearly wrong. Here is my code:

public class Statistics
{

    public static void main(String[] args)
    {
        int[] nums = new int[]{5, 2, 1, 6, 7};

        printArray(nums);
        average(nums);
        double store = average(nums);
        System.out.println(store);
    }


    public static void printArray(int[] nums) {
        for(int i = 0; i < nums.length; i++){ 
            System.out.print(nums[i]); 
            }
    }


    public static double average(int[] values) {
        int sum = 0;
        double average;

        for(int i=0; i < values.length; i++){
            sum = sum + values[i];
        }
        average = (double)sum/values.length;
        return average;   

Actually, it printed the array ( 52167 ) and then the average ( 4.2 ).

To improve this, you may want to have a System.out.println(); at the very end of printArray , so that the output is on its own line.

You may also want to have a separator, like , , so that it prints 5,2,1,6,7 . For example:

public static void printArray(int[] nums) {
    for (int i = 0; i < nums.length - 1; i++) { 
        System.out.print(nums[i]);
        System.out.print(","); 
    }
    if (nums.length > 0) { // make sure array isn't empty
        System.out.println(nums[nums.length - 1]);
    }
}

There's nothing wrong with your code. You're getting confused due to the output.

If you comment the line that deals with printArray() , or change its System.out.print() to System.out.println() , then you'll see the results you expect.

Currently your code is printing the contents of the array AND the average on the same line with no space in between. Remove the printArray() call and you can see that it will output only the average 4.2 , which is correct:

public static void main(String[] args) {
    int[] nums = new int[] { 5, 2, 1, 6, 7 };

    //printArray(nums);
    average(nums);
    double store = average(nums);
    System.out.println(store);
}

您应该使用.println()而不是print(),这会很好

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