gpt4 book ai didi

c++ - Clang-tidy 不正确的舍入

转载 作者:行者123 更新时间:2023-11-30 02:16:06 26 4
gpt4 key购买 nike

clang-tidy 文档 [bugprone-incorrect-roundings]检查说:

The number 0.499999975 (smallest representable float number below 0.5) rounds to 1.0

据我所知,0.5 以下的最小 float 是 0.4999999702,而不是 0.499999975。但尽管如此,这两个数字 give me 0 values在简单的舍入计算中:

#include <iostream>

int main() {

const float v1 = 0.499999975;
const float v2 = 0.4999999702;

std::cout << (int)(v1+0.5) << "\n"
<< (int)(v2+0.5) << "\n";
}

我错过了什么吗?

最佳答案

关于标准中的算术转换:

6.3.1.8 Usual arithmetic conversions

...

  • Otherwise, if the corresponding real type of either operand is double, the other operand is converted, without change of type domain, to a type whose corresponding real type is double.

  • The values of floating operands and of the results of floating expressions may be represented in greater precision and range than that required by the type;

所以在这一行中:

(int)(v1+0.5) 

您的 v1 变量被提升为 double 浮点运算,这就是您得到零的原因。

这应该可以解决您的问题:

#include <iostream>

int main() {

const float v1 = 0.499999975f;
const float v2 = 0.4999999702f;

std::cout << (int)(v1 + 0.5f) << "\n"
<< (int)(v2 + 0.5f) << "\n";
}

关于c++ - Clang-tidy 不正确的舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55373980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com