-1

I apologize for the simplicity of this question but I have a test question for a online exam and it is asking me to solve this problem:

public class MathUtils {
    public static double average(int a, int b) {
        return (a+b)/2;
    }

    public static void main(String[] args) {
        System.out.println(average(2, 1));
    }
}

There are two test classes that I can not see, I just have to solve for the test class error messages they return. The error I am getting back is:

Integer division wrong answer

1.5 is the answer, which is a double...so I am not sure how this could be the wrong number. I think I am loosing it, so if someone please point out what I am missing I would greatly appreciate it!

Olivia
  • 941
  • 7
  • 28
  • 8
    `return (a+b)/2.0;` (`a`, `b` and `2` are all `int`, thus integer math). – Elliott Frisch Feb 12 '20 at 14:46
  • Try a non-integer division that acutally gives you decimal places... The one @ElliottFrisch just commented should be a good point to start. – deHaar Feb 12 '20 at 14:47
  • @ElliottFrisch thank you! – Olivia Feb 12 '20 at 14:47
  • 6
    Does this answer your question? [Int division: Why is the result of 1/3 == 0?](https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0) – AndiCover Feb 12 '20 at 14:48
  • @Olivia Just be aware `2` is not special, any one of the terms should be a `double`. E.g. `return ((double)a+b)/2; or `return (a+(double) b)/2;` or even `return (a+b)/(double) 2;` you were widening the integer result. – Elliott Frisch Feb 12 '20 at 14:49

3 Answers3

0

You must either use doubles to do non integer division. Integer division gives back an integer thus 3/2 = 1 because its 1.5 which is truncated into 1. To get an double result, you must either use doubles as a type or cast the integers to doubles.

public static double average(int a, int b) {
        return (a+b)/2.0; // making it 2.0 makes it a double.
}

or

public static double average(int a, int b) {
        return (a+b)/(double)2; // making it 2.0 makes it a double.
}

This forces it to give you a double back, giving the expected result

tyhdefu
  • 70
  • 6
0

Your code is giving you an error because when you divide 3 by 2 your answer is 1.5 which is a double not an integer. So you need to use explicit casting for the result of your answer or change your method types to double's

0

You have to upcast integer data type to double data type as like below

public class Main {

    public static double average(int a, int b) {
        return (double)(a+b)/2;
    }

    public static void main(String[] args) {
        System.out.println(average(2, 1));
    }
}
pedrohreis
  • 821
  • 2
  • 11
  • 28