MSVC brace initialization with doubles appears to violate the standard?

前端 未结 2 1178
长情又很酷
长情又很酷 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: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 };
    

提交回复
热议问题