Can cout alter variables somehow?

前端 未结 2 1216
被撕碎了的回忆
被撕碎了的回忆 2021-02-08 16:32

So I have a function that looks something like this:

float function(){
    float x = SomeValue;
    return x / SomeOtherValue;
}

At some point,

2条回答
  •  忘掉有多难
    2021-02-08 17:07

    Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with.

    This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register).

    When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases.

    See the MSDN documentation on VC++ floating point switches. You could try compiling with /fp:strict and seeing what happens.

提交回复
热议问题