I\'m fairly new to C++ and I\'m experiencing some strange behaviour from a percentage increase method I am writing for some image editing software.
What I want to do is
Do this:
// calculate return value
double returnVal = (static_cast(currPixel) / modifier) * newValue;
Or this:
double returnVal = (currPixel / static_cast(modifier)) * newValue;
As you know that operator /
will be performed first, and then the operator *
. I have typecasted one of the operands of /
to double
, and hence division will be performed double
. Now, left operand of *
would be double
(since /
produced double
), and the multiplication would be performed double
also. For clarity and correctness, you may write:
double returnVal = (static_cast(currPixel) / static_cast(modifier)) * static_cast(newValue);
Or simply:
double returnVal = (double(currPixel) / (double)modifier) * (double)newValue;
But, following is WRONG:
double returnVal = (double)(currPixel / modifier) * /*(double)*/ newValue;
Since the division would be performed int
only! It is like:
double x = 10/3;
Where you need (either):
double x = 10.0/3;
double x = 10/3.0;
double x = (double)10/3;