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!
In this expression
the both operands of the binary operator
/have the typeint. So there is used the integer arithmetic and the result of the expression is1.In this expression
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.