-1

I'm having some difficulty understanding why the output differs. Hopefully, someone can explain what's going on here.

The below code calculates the volume and surface area as expected (33.5103 and 50.2655, respectively) when I enter 2, but if I change the equation for Volume from (4.0 / 3) * Math.PI * Math.pow(r, 3); to (4 / 3) * Math.PI * Math.pow(r, 3);, the output is 25.1327

Why is the output different when I change 4.0 to 4?

import java.lang.Math;  // Import the Math class.
import java.util.Scanner;  // Import the Scanner class.
import java.text.DecimalFormat; // Import the DecimalFormat class.

class Main {

  public static double calcVolume(double r) {
    // Return Volume.
    return (4.0 / 3) * Math.PI * Math.pow(r, 3);
  }

  public static double calcSurfaceArea(double r) {
    // Return the Surface Area.
    return 4 * Math.PI * Math.pow(r, 2);
  }

  public static void main(String[] args) {

    // Prompt user for the radius.
    Scanner radius_in = new Scanner(System.in);
    System.out.println("Please enter the radius to calculate volume and surface area: "); 

    Double radius = radius_in.nextDouble();

    Double volume = calcVolume(radius);
    Double surfaceArea = calcSurfaceArea(radius);

    // Set up decimalformat object for outputting to 4 decimal places.
    DecimalFormat DF = new DecimalFormat("0.####");

    System.out.println("Volume is: " + DF.format(volume));
    System.out.println("Surface Area is: " + DF.format(surfaceArea));

  }
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
David Metcalfe
  • 2,237
  • 1
  • 31
  • 44
  • 1
    Perhaps not a duplicate, but read https://stackoverflow.com/questions/4685450/int-division-why-is-the-result-of-1-3-0 anyway. – High Performance Mark Aug 06 '19 at 04:45
  • 2
    `4.0 / 3` is `1.33...`; `4 / 3` is `1`. The division will be integral unless at least one argument is floating. – Amadan Aug 06 '19 at 04:45
  • Because of 4/3 returns 1, whereas 4.0/3 returns 1.333 – raviraja Aug 06 '19 at 04:45
  • 1
    Revise the title of this Question to summarize more specifically your particular technical issue. How is your question distinct from all the other java.lang.Math questions? – Basil Bourque Aug 06 '19 at 05:31

1 Answers1

1

It's because with 4.0 / 3 you're getting a floating point precision, whereas 4 / 3 is considered as int. This means, that whatever is evaluated as 4 / 3, the decimal part is cut off:

4.0 / 3 => 1.(3)
4 / 3 => (int) (1.(3)) => 1
Andronicus
  • 25,419
  • 17
  • 47
  • 88