I know this is kinda of a dumb question but I was hoping someone could help me on this.
I know math and I know C++ evaluates from left to right using associative priority but I can't figure out, even after doing some pretty extensive reading and searching, why a couple of the variables in the following code I'm messing with outputs zeros.
#include <iostream>
usingnamespace std;
int main()
{
int a = 7 * 9 - 3 + 5;
double b = 3 / 4 * 6;
int c = 5 / 1 * 2;
int d = 2 * 2 * 3 / 4;
double e = 2 / 3 * 3 / 3;
cout <<" a: " << a << endl;
cout <<" b: " << b << endl;
cout <<" c: " << c << endl;
cout <<" d: " << d << endl;
cout <<" e " << e << endl;
return 0;
}
The above code isn't homework, it's just code I'm messing with after reading C++ Primer. B and E are outputting zero's and I'm not sure why.
Aren't doubles supposed to be able to handle fractional values? B should equal to 4.5 and E should be 0.67 (I'm rounding up here) using basic arithmetic. Am I missing something? I've tried experimenting with different variations but it still outputs zeros.
Never mind, I figured it out. I didn't use the following format:
1 2 3 4
double b = 3.0 / 4.0 * 6.0;
double e = 2.0 / 3.0 * 3.0 / 3.0;
I left off the .0 at the ends of the numerical values.
I'm bit confused though. Aren't values that have been declared as floating point or double supposed to output fractional values regardless of not having .0 attached to the original value? I thought C++ did that for you automatically.
I've been there man... I had my program output tons and tons of garbage values before realizing that C++ does NOT initialize them with automatic decimals... And i could have sworn i had read that C++ does just that.