0
import java.util.Scanner;

public class test {

    private static int number1 = 100;
    private static int number2 = 1;

    public static double avgAge() {

        return (number1 + number2) / 2;
    }

    public static void main(String[] args) {

        System.out.println("Average number: " + test.avgAge());
    }   
}

Why does test.avgAge() = 50.0 instead of 50.5? Is there a way to output 50.5 instead?

jpw
  • 44,361
  • 6
  • 66
  • 86
Azaria Gebo
  • 11
  • 1
  • 2
  • 3

5 Answers5

3

The calculation is done as an integer calculation.

If you replace 2 by 2.0 you will get 50.5. I recommend adding a comment to that line to explain this to future readers. Alternatively you can explicitly cast to a double:

((double) (number1 + number2)) / 2
CompuChip
  • 9,143
  • 4
  • 24
  • 48
2

Just replace this function

import java.util.Scanner;

public class test {

private static int number1 = 100;
private static int number2 = 1;

public static double avgAge() {

    return (number1 + number2) / 2.0;
}

public static void main(String[] args) {

    System.out.println("Average number: " + test.avgAge()); //Average number: 50.5
}   
}
shankar
  • 632
  • 4
  • 14
0

It's because you're using ints through out the calculation before returning it as a double. Do the following:

private static double number1 = 100.0;
private static double number2 = 1.0;

Change these to double. Also, change the 2 to 2.0:

    return (number1 + number2) / 2.0;

Read more about ints and doubles here:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

0

That's because of type promotion.

If in an operation, any of the operands is a double, then the result is promoted to double.

Since here all operands are ints, the division results in an int.

Type Promotion

coding_idiot
  • 13,526
  • 10
  • 65
  • 116
-2
return ((double)(number1 + number2)) / 2;
SchmitzIT
  • 9,227
  • 9
  • 65
  • 92
L Q
  • 101