I was playing around with C++ today and this is what I found after doing some tests:
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = myInt + (0.5 * 17); // the math inside the parentheses should go first
int difference = myInt2 - myInt; // get the difference of the two numbers
cout << difference << endl; // difference is 8
}
the output is 8
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = myInt - (0.5 * 17); // the math inside the parentheses should still go first
int difference = myInt - myInt2; // get the difference of the two numbers
cout << difference << endl; // difference is 9?
}
The output is 9?
So according to my first code sample, 0.5 * 17 = 8, but according to my second code sample, 0.5 * 17 = 9. I am aware that I would get the same results without the parentheses, but I am using them to help illustrate what I am doing in my code.
To help narrow down the problem, I tried this:
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = 0.5 * 17; // use a variable instead of parentheses
int myInt3 = myInt + myInt2;
int difference = myInt3 - myInt; // get the difference of the two numbers
cout << difference << endl; // difference is 8
}
the output is 8
#include <iostream>
using namespace std;
int main()
{
int myInt = 100;
int myInt2 = 0.5 * 17; // continue using a variable
int myInt3 = myInt - myInt2;
int difference = myInt - myInt3; // get the difference of the two numbers
cout << difference << endl; // difference is 8 again!
}
the output is 8 again!
So my question is, if the math in the parentheses always comes first, then why am I getting different results? Shouldn't the first two trials have the same results as the second two trials? Another thing I should mention is that I have had these same results with other decimal numbers like 0.1 and 0.3.