Beginner JAVA arithmetics/Math

ZKR

Honorable
Mar 12, 2012
35
0
10,580
0
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(?!):
Code:
import java.util.Scanner;
import java.text.DecimalFormat;

public class Sphere
{
	public static void main (String[] args)
	{
	Scanner scan = new Scanner (System.in);
	double radius, volume, surfaceArea, val;
	
	System.out.print ("Please enter sphere radius : ");
	radius = scan.nextDouble();
	
	volume = (double) 4/3 * Math.PI * Math.pow (radius, 3);	// [u]Lack of (double) conversion gave the result of:
	// 4/3 = 1 because of automatic integer conversion? and not 1.333333333333333[/u]
	
	surfaceArea = 4 * Math.PI * Math.pow (radius, 2);
	val = 4/3;													[u]//example of result in a double value converted to integer[/u]
	
	DecimalFormat fmt = new DecimalFormat ("0.####");
	
	System.out.println ("Sphere volume : " + fmt.format(volume));
	System.out.println ("Sphere surface area : " + fmt.format(surfaceArea));
	System.out.println ("4/3 = : " + val);                                                    [u]//example of result in a double value converted to integer - Printed[/u]
	}
}
// result of val = 4/3;	 is 1, not 1.333333333333333 but it`s a double.
Can someone explain please.
 

Ijack

Distinguished
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.
 

Ijack

Distinguished
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.
 

ZKR

Honorable
Mar 12, 2012
35
0
10,580
0
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
 
Thread starter Similar threads Forum Replies Date
B Apps General Discussion 23
B Apps General Discussion 2
I Apps General Discussion 2
K Apps General Discussion 3
G Apps General Discussion 14
syssoft Apps General Discussion 1
C Apps General Discussion 9
C Apps General Discussion 6
A Apps General Discussion 8
M Apps General Discussion 4
C Apps General Discussion 1
tomsguideUS Apps General Discussion 3
D Apps General Discussion 4
H Apps General Discussion 3
H Apps General Discussion 8
seperoph Apps General Discussion 3
Moroz Academy Apps General Discussion 0
Moroz Academy Apps General Discussion 0
Moroz Academy Apps General Discussion 0
Z Apps General Discussion 11

ASK THE COMMUNITY