Help with java math

• 10-25-2010, 01:09 PM
gabrielfirestorm
Help with java math... SOLVED
Code:

```import java.util.Scanner; public class Sphere {         public static void main(String [] a)         {                 System.out.println("This program prints surface area and volume");                 System.out.println("of spheres for radii ranging from 10 to N,");                 System.out.print("in increments of 10. Please input the value of N: ");                 Scanner userInput = new Scanner(System.in);                 int valueOfN = userinput.nextInt();                 double pi = 3.14;                 System.out.println("---------------------");                 System.out.println("\t\tSurface");                 System.out.println("r\tArea\tVolume");                 System.out.println("---------------------");                                 for(int r = 10; r <= valueOfN; r += 10)                 {                         System.out.print(r + "\t" + (4*pi*(r*r)) + "\t" + (4/3*pi*(r*r*r)));                 }         } }```
hi everyone, im currently in university doing an intro to java course and we were give some sample questions from the previous years midterm to try out. I wrote this in order to find surface area and volum of a sphere from radii 10 to N. other than some rounding issues the surface area works however the volume doesn't. it appears to me when running the program that all it will do is the math of pi*r^3 but completely leave out the 4/3. anyone have an idea of either why its doing that or how I can fix it. I've tried rewriting the math several ways but still appears to be doing the same thing with omitting the 4/3
• 10-25-2010, 01:13 PM
JosAH
4/3 == 1 because both 4 and 3 are integers so integer division is used. Use 4.0/3.0 instead; oh, b.t.w. the Math class has a better approximation for pi.

kind regards,

Jos
• 10-25-2010, 01:14 PM
Eranga
Seems your question is not a valid one, it's 0.75 x pi x r3 or other way?
• 10-25-2010, 01:14 PM
do "4/3.0" or "4/(double) 3" or something similar. bare numbers in code without decimals are integers and integer math can only produce integers, thereby making 4/3 = 1.

Edit: Man, am I slow.
• 10-25-2010, 01:18 PM
Eranga
Quote:

Originally Posted by Eranga
Seems your question is not a valid one, it's 0.75 x pi x r3 or other way?

Sorry guys. Seems my knowledge in maths is not good. Misses fundamentals here. :o
• 10-25-2010, 01:22 PM
gabrielfirestorm
thank you very much that explains everything :)
• 10-25-2010, 01:54 PM
JosAH
Quote:

Originally Posted by Eranga
Seems your question is not a valid one, it's 0.75 x pi x r3 or other way?

That's an incorrect formula; the volume of a sphere is 4/3*pi*r^3.

kind regards,

Jos

edit: darn, where do all those answers come from all of a sudden? ;-)