Uses for negative zero floating point value?

前端 未结 5 1358
天命终不由人
天命终不由人 2020-12-03 04:53

Consider the following C++ code:

double someZero = 0;
std::cout << 0 - someZero << \'\\n\';   // prints 0
std::cout << -someZero << s         


        
5条回答
  •  遥遥无期
    2020-12-03 05:47

    I'm making a measuring app, and the -0 is very useful for mixed numbers (such as separating into feet and inches).

    Imagine that we have a variable "length" that we're trying to separate into "feet" and "inches".

    (This is java code, but the same idea is true for C++).

    feet = Math.signum(length) * Math.floor(Math.abs(length / 12));
    // could also do feet = length>0 ? Math.floor(length / 12) : Math.ceil(length / 12)
    inches = Math.abs(length) % 12;
    

    If the length is between -1 feet and 0 feet, we'd want it to say -0 for the feet so we know it's negative.

提交回复
热议问题