Clang-tidy 不正确的舍入
Clang-tidy incorrect rounding
clang-tidy 的文档[bugprone-incorrect-roundings] 检查说:
The number 0.499999975 (smallest representable float number below 0.5) rounds to 1.0
据我所知,0.5
下面的最小浮点数是 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
变量被提升为双精度浮点运算,这就是您得到零的原因。
这应该可以解决您的问题:
#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";
}
clang-tidy 的文档[bugprone-incorrect-roundings] 检查说:
The number 0.499999975 (smallest representable float number below 0.5) rounds to 1.0
据我所知,0.5
下面的最小浮点数是 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
变量被提升为双精度浮点运算,这就是您得到零的原因。
这应该可以解决您的问题:
#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";
}