MSVC brace initialization with doubles appears to violate the standard?

前端 未结 2 1174
长情又很酷
长情又很酷 2021-01-17 18:05

Check out this simple program:

int main() {
    float f2 = 7.2; // OK, with warning
    float f3 = 7.199999809265137; // OK, no warning
    float f4{ 7.2 };          


        
相关标签:
2条回答
  • 2021-01-17 18:18

    It looks like a bug, indeed. For a workaround, the following appears to silence both errors and warnings in MSVC 2015.

    #pragma float_control(precise, off, push)
    
    float f2 = 7.2; // OK, with warning
    //...
    
    #pragma float_control(precise, pop)
    

    The same works globally if using the /fp:fast compiler switch, though that one is incompatible with /Za which disables MS language extensions.

    0 讨论(0)
  • 2021-01-17 18:34

    Some floating point numbers can be exactly expressed in a float representation and some can't. If the number can be represented in the form x / 2^y where x is any integer and y is an integer 23 or less, it fits. Most decimal numbers can't be represented in this way, as a binary number they repeat forever. 7.2 is one example.

    You can fix this easily by appending f to each number, to indicate to the compiler that this is a float constant rather than a double.

    float f4{ 7.2f };
    
    0 讨论(0)
提交回复
热议问题