Sign in with
Sign up | Sign in
Your question
Solved

Beginner JAVA arithmetics/Math

Last response: in Applications
Share
April 3, 2012 10:13:21 PM

Hello.
An app I had to make for calculating sphere`s volume and surface area.
The code didn`t give the correct result for volume until I cast converted it`s value by adding (double), but it is a double from the beginning(?!):
  1. import java.util.Scanner;
  2. import java.text.DecimalFormat;
  3.  
  4. public class Sphere
  5. {
  6. public static void main (String[] args)
  7. {
  8. Scanner scan = new Scanner (System.in);
  9. double radius, volume, surfaceArea, val;
  10.  
  11. System.out.print ("Please enter sphere radius : ");
  12. radius = scan.nextDouble();
  13.  
  14. volume = (double) 4/3 * Math.PI * Math.pow (radius, 3); // [u]Lack of (double) conversion gave the result of:
  15. // 4/3 = 1 because of automatic integer conversion? and not 1.333333333333333[/u]
  16.  
  17. surfaceArea = 4 * Math.PI * Math.pow (radius, 2);
  18. val = 4/3; [u]//example of result in a double value converted to integer[/u]
  19.  
  20. DecimalFormat fmt = new DecimalFormat ("0.####");
  21.  
  22. System.out.println ("Sphere volume : " + fmt.format(volume));
  23. System.out.println ("Sphere surface area : " + fmt.format(surfaceArea));
  24. System.out.println ("4/3 = : " + val); [u]//example of result in a double value converted to integer - Printed[/u]
  25. }
  26. }
  27. // result of val = 4/3; is 1, not 1.333333333333333 but it`s a double.


Can someone explain please.

Best solution

a b L Programming
April 4, 2012 6:31:28 AM

I think you have answered your own question in your comments. 4 / 3 = 1, as both are integers. (double) 4 is a double, so (double) 4 / 3 = 1.3333....

You would get the same result by using 4.0 / 3 or 4.0 / 3.0.
Share
April 8, 2012 1:24:49 PM

Yes it gave the same result with 4.0 (and so 3 converted by promotion to 3.0 too).
I thought it`s the variable type that counts.

Thanks
m
0
l
April 30, 2012 10:46:00 PM

Best answer selected by ZKR.
m
0
l
!