Search code examples
c++mathvisual-c++arithmetic-expressions

Arithmetic calculation anomaly


I was trying to solve this exercise. Here is the solution:

#include <iostream>

using std::cout;
using std::cin;

int main()
{
    int n, a;
    cin >> n;
    int* answers = new int[n]; // allocating memory
    for (int i = 0; i < n; i++)
    {
        cin >> a;
        answers[i] = (a - 32) * 5/9;
    }

    for (int i = 0; i < n; i++)
    {
        cout << answers[i] << ' ';
    }

    cout << '\n';
    delete[]answers; //deallocating memory

    system("pause");
    return 0;
}

Now, notice when I change answers[i] = (a - 32) * 5/9; to answers[i] = (a - 32) * (5/9);.
Here, is the difference in the output respectively:

  1. Without the brackets:

    enter image description here

  2. With the brackets:

    enter image description here

What is this sorcery?

EDIT:

I understand why this can seem as a duplicate. My concern is not why 5/9 outputs 0. That is not my concern. My concern is what is the difference between the two following code:

  • answers[i] = (a - 32) * 5/9;
  • answers[i] = (a - 32) * (5/9);

When I do not use brackets, it works. But, when I use brackets it just outputs 0. So, the question is what is the bracket operator changing here? Please read the question carefully.


Solution

  • In (a - 32) * 5/9; the expression is done from left to right as ((a - 32) * 5)/9 because * and / have the same precedence with left-to-right associativity

    If you do (a - 32) * (5/9) then it's exactly the same as (a - 32) * 0 because the expressions in () are done first, and 5/9 is an integer division that results in 0. To do a floating-point division then at least one side of the division must be a floating-point type. Try (a - 32) * (5.0/9) or (a - 32) * (5/9.0) and see