Order of Operations problem.

I'm not sure if the problem is because of how the compiler handles nested order of operations or if it is because of the casting between two types.

const int size = 5;

//gives zero. not what it should be.
const double result = (size / ((size - 1) * (size - 2)));

//split it apart...with result getting the correct value of 0.416666...
const double temp = (size - 1) * (size - 2);
const double result = size / temp;

This problem is making me feel like a complete noob.
PS: This is being used in a routine for calculating skewness if that helps.
This has nothing to do with order of operations, it's because you're dividing two integers, which always yields another integer as a result. You need to cast at least one of the operands to a floating point number.
the problem is that size is an integer. if you divide an integer by an integer guess what you get? an integer. you need to do
const double result = ((size * 1.0) / ((size - 1) * (size - 2)));
the 1.0 makes the number a float. note that it will always go to the lowest decimal place allowed in the data type. and your are also restating a const variable here
const double result = size / temp; this will throw an error.
Thank you. I ended up declaring size as a double to fix it.
that works also.
Topic archived. No new replies allowed.