What is the difference between 4/3 and 4/3.0?

1.1k views Asked by At

I need to make a program to calculate the volume of a sphere with the formula V=(4/3)*pi*r^3

What is the difference between

volume_sphere = (4/3)*pi*r*r*r; 

and

volume_sphere = (4/3.0)*pi*r*r*r; 

?

When I input the 3 as the value for my r, the former gave me a wrong answer (84.823196). However, when I used the latter one (with the ".0"), it gave me the right answer (113.0976).

I am so confused with the ".0" difference. Thank you for answering!

2

There are 2 answers

0
Vlad from Moscow On

In this expression

4/3

the both operands of the binary operator / have the type int. So there is used the integer arithmetic and the result of the expression is 1.

In this expression

4/3.0

the second operand is a constant of the type double. So the first operand also is converted to the type double due to the usual arithmetic conversions. And the result of the operation is a floating point number. That is there is no truncation of the fraction part of the result to the integer value.

0
eito-okada On

4 / 3 = 1, while 4 / 3.0 = 1.333333...

Dividing an integer by an integer will result in an integer, but the ".0" makes the answer have decimals.