Programming Rage
Programming Rage

Reputation: 414

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:

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.

Upvotes: 0

Views: 86

Answers (3)

user9706
user9706

Reputation:

With the brackets you are evaluated (int) 5 / 9 which is 0. Without the brackets, you are seeing the effect of * and / having the same operator precedence and they are evaluated left to right which means the expression would be evaluated as ((a - 32) * 5) / 9.

If you are doing fractional math, you usually assign the value to a floating point type (float, double etc). If you want indeed want the result as an int, you may still want to do the calculation as a floating point, and you usually do that implicitly by making one of the constants a floating point type like 5.0 / 9.

Upvotes: 1

phuclv
phuclv

Reputation: 42032

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

Upvotes: 2

mascai
mascai

Reputation: 1882

According to the C++ 5 / 9 is 0, because 5 and 9 are integers. You should use double.

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.0; // 9.0 is double
    }

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

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

    system("pause");
    return 0;
}

Upvotes: 2

Related Questions