Mathematical Order Confusion

Hi there,

I'm wondering if anyone can clarify a code for me.
I'm trying to understand the order of operation as it's quite confusing me.

The equation is:
a / (r1 / r1 + a * r1 - a * r1)

From my understanding of logic, I assume this code is supposed to be:
a / (r1 / ( (r1+a)*(r1-a)*r1 )

But this would simplify to 1 / ( (r1+a)*(r1-a) ) which seems wrong as it's stupid to include those terms that cancel.

I've also had a similar issue with the code x + 1.0 * (y - x) / 8.0 + z

Is it x + (1/8)*(y - x) + z or (x + (1.0*(y-x)) / (8.0 + z) ?

I'm really confused and the internet hasn't been very helpful.

How do I figure this out?
a / (r1 / r1 + a * r1 - a * r1)

That will always give the answer: a. You can try it.
1
2
3
4
5
6
#include <iostream>
int main()
{
   double a = 4.0, r1 = 5.0;
   std::cout << a / (r1 / r1 + a * r1 - a * r1);
}



* and / take priority ("precedence") over + and -, so (within a bracket) they will be done first.

Brackets will also be completed before anything else.

You can find the complete order of precedence at
https://en.cppreference.com/w/cpp/language/operator_precedence
You only need items 5 and 6 in that list. For numerical operations, the order of calculation is the same as standard arithmetic. You don't need the internet for that.

Roughly:
a / (r1 / r1 + a * r1 - a * r1)      ->     a / ( 1 + value - value )    -> a / 1      ->  a





dialgpalkia wrote:
From my understanding of logic

Your understanding of logic is wrong. You are (incorrectly) doing + and - before * and /.
Last edited on
Topic archived. No new replies allowed.