输出到具有精度的流浮点数 [英] output to stream float numbers with precision
问题描述
我对浮点数精度有疑问:
int main(void) {
double b = 106.829599;
float a = b;
std::cerr << std::setprecision(6) << "a = " << a << "; b = " << b << std::endl;
std::cerr << std::setprecision(7) << "a = " << a << "; b = " << b << std::endl;
}
结果是:
a = 106.83; b = 106.83
a = 106.8296; b = 106.8296
所以,我的问题是为什么第一行中的数字这么短(我原本希望看到106.829)
gcc 4.1.2,我也在 LWS
进行了测试实际上,将106.829599舍入为6位数字(3位小数)是106.830,由于对已修复结合在一起./p>
I have a problem with float numbers precision:
int main(void) {
double b = 106.829599;
float a = b;
std::cerr << std::setprecision(6) << "a = " << a << "; b = " << b << std::endl;
std::cerr << std::setprecision(7) << "a = " << a << "; b = " << b << std::endl;
}
result is:
a = 106.83; b = 106.83
a = 106.8296; b = 106.8296
So, my question is why numbers in first line are so short (I was expecting to see 106.829)
gcc 4.1.2, also I made a test at LWS
Actually, 106.829599 rounded to 6 digits (3 decimals) is 106.830, which is displayed as 106.83 since 6 digits precision given to setprecision is only a maximum value.
The decimal precision determines the maximum number of digits to be written on insertion operations to express floating-point values.
What you may be looking for is combining setprecision with fixed.
这篇关于输出到具有精度的流浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!