0

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!

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Llrence
  • 17
  • 1
  • 1
    `3` is an `int` literal, `3.0` is a `double` literal. Using `.0` is the idiomatic way of ensuring a numeric literal is typed as `double`. You can use `f` as a suffix instead of `.0` to use `float` (single-precision) instead of `double` or use `l` or `L` for `long double`. – Dai Oct 28 '21 at 09:06
  • 3
    Without the `.0` you have an integer literal and `4/3` performs integer division (which yields `1`) – UnholySheep Oct 28 '21 at 09:06
  • 1
    Because both `4` and `3` are integers, the division `4 / 3` is an integer division with an integer result. If one of the numbers is a floating-point number (`3.0` is a `double` value) then it will become a floating-point operation with a floating-point result. – Some programmer dude Oct 28 '21 at 09:06
  • 1
    Another option would be `pi * r * r * r * 4 / 3`. The removal of the parentheses means that `4 / 3` isn't calculated independently of the rest of the expression. – Weather Vane Oct 28 '21 at 09:09
  • 1
    As @WeatherVane notes, the order of operations is important, and the operator priority of those operations is, too. Because you have a parenthesized operation, it is resolved first; if you had a "mathematically-equivalent" operation where one operand was already floating-point, the result would also have been calculated as floating-point. – tucuxi Oct 28 '21 at 09:14

2 Answers2

1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

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.

eito-okada
  • 29
  • 8