0

I am trying to calculate the volume of a sphere given the radius as a user input. Pi is defined as a constant in my program, and I am using the pow function.

For some reason, I get different results when I switch the order of the 4/3 and the PI. Here is some code to further explain:

const double PI = 3.141593;

int main()
{
    double radius;
    double volume;
    cout << "Enter the radius of a sphere, and the volume will be given." << endl;
    cin >> radius;
    volume = 4 / 3 * PI * (pow(radius, 3));
    cout << "The volume of a sphere with radius " << radius << " is " << volume << endl;
}

The correct answer is only displayed when the constant is placed at the beginning of the expression. For example, when 3 is entered as the radius, the answer is 84.823. But when that expression is displayed like this:

volume = PI * 4 / 3 * (pow(radius, 3));

the answer is 113.097. What is the reason for this?

  • 2
    Change that 4 to `4.0`, otherwise you are performing integer division. – PaulMcKenzie Oct 20 '19 at 01:48
  • 2
    Also, you don't need any input statements. You could have a full program and eliminate more than half the code that you posted, [as this example shows](http://coliru.stacked-crooked.com/a/64e923b02b4ef771). – PaulMcKenzie Oct 20 '19 at 02:00
  • FYI, if the 4 and 3 were integer variables, you could use `(double) a / (double) b` to force them to be treated as floating point. – Dave S Oct 20 '19 at 02:15
  • Because division, multiplication, addition, and subtraction are all left-to-right associative and because of rules of type promotion. `4/3*PI` works by calculating `4/3` as a group (which gives an `int`, i.e. `1` not `1.333...`) and the multiplication by `PI` promotes the `1` to `double` before multiplying - so the overall result is `PI`. Whereas `PI * 4 / 3` computes `PI*4` as a group (promotes `4` to `double` and multiplies), giving a result of type `double` equal to `4.0*PI`. `3` is promoted to `double` before dividing, and the overall result is equal to one and one-third times `PI` – Peter Oct 20 '19 at 02:26

0 Answers0