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));
}
}