Results 1 to 4 of 4
Thread: Exercises
- 09-14-2009, 05:56 PM #1
Member
- Join Date
- Aug 2009
- Posts
- 22
- Rep Power
- 0
Exercises
I have a question about priniting out volume and surface area of a sphere.
I have written out the code, However, I am unable to obtain the correct output for the volume. May I know where is my mistake?
Belows are my work out code.
<code> int radius;
double volume,surfaceArea;
//final double PI = 3.142;
Scanner scan = new Scanner(System.in);
System.out.print("Give the radius of circle: ");
radius = scan.nextInt();
volume = (double)((4/3)*Math.PI*Math.pow(radius,3));
surfaceArea = (double)(4*Math.PI*Math.pow(radius,2));
DecimalFormat fmt = new DecimalFormat("0.####");
System.out.println("The circle's volume is "+fmt.format(volume)+" and it's surface area is "+fmt.format(surfaceArea)+'.');
</code>
Thank you for any help and reply.
-
Change (4/3) to ((double)4/3) if you want to avoid int division here. Perhaps even better would be to just use double numeric constants:
(4.0/3.0)
- 09-14-2009, 06:03 PM #3
Member
- Join Date
- Aug 2009
- Posts
- 22
- Rep Power
- 0
Thank you Fubarable.
But, May I know why is this so?
thank you for your help.
-
(4/3) will result in int division which returns an int (it will return 1 in fact). You don't want int division, but rather want floating point division so that you can have a floating point result returned.thank you for your help.


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks