C++, my double or int value is always 0

前端 未结 5 397
没有蜡笔的小新
没有蜡笔的小新 2021-01-25 14:32

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

5条回答
  •  有刺的猬
    2021-01-25 15:14

    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;
    

提交回复
热议问题