1

So I was doing an easy problem to calculate the volume of a sphere which is 4/3 * PI * R³ (R= radius of it)

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main() {


    double R, pi = 3.14159, volume = 0;

    cin >> R;

    volume = 4/3 * pi * R * R * R;

    std::cout << std::fixed << std::setprecision(3) << "VOLUME = " << volume << endl;

    return 0;
}

I've noticed that it gives me the wrong answer but when I change the calculation of volume to:

volume = R * R * R * pi * 4/3;

It does give me the right answer. So... Why? Am I doing something wrong here?

  • 2
    Try `std::cout << 4/3 << std::endl;` and see the answer yourself. – Sam Varshavchik Jul 24 '22 at 00:10
  • There are actually two factors at play in this question. Multiplication and division have the same precedence and are left to right associative. So `4/3 * pi * R * R * R` is calculated as `(4/3) * pi * R * R * R` which causes `4/3` to be calculated as an `int` with value `1` (since both `4` and `3` have type `int`). `R * R * R * pi * 4/3` does not do `int` calculations as it is calculated as `(R * R * R * pi *4)/3` which promotes the `4` to `double` and calculates `(R * R * R * pi *4)` as a `double` - which causes `3` to also be promoted to `double` and divided - also producing a `double`. – Peter Jul 24 '22 at 00:33

1 Answers1

1

I believe your problem is here:

volume = 4/3*pi*R*R*R;

In particular 4/3 is dividing integer 4 by integer 3, which results in an integer result of 1; probably not what you intended. I think you want this instead:

volume = 4./3.*pi*R*R*R;

(note the periods; that tells C++ that the values should be double-precision floats rather than integers, so you won't get the massive rounding error)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234