如何“cout”正确的小数位数的双精度值? [英] How to 'cout' the correct number of decimal places of a double value?

查看:654
本文介绍了如何“cout”正确的小数位数的双精度值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助保持 double 的精度。如果我将一个文字指定为double,则实际值被截断。

I need help on keeping the precision of a double. If I assign a literal to a double, the actual value was truncated.

int main() {
    double x = 7.40200133400;
    std::cout << x << "\n";
}

对于上述代码片段,输出为 7.402

有没有办法防止这种类型的截断?或者有办法计算 double 的浮点数多少?例如, number_of_decimal(x)会给出11,因为输入在运行时是未知的,所以我不能使用 setprecision code>。

For the above code snippet, the output was 7.402
Is there a way to prevent this type of truncation? Or is there a way to calculate exactly how many floating points for a double? For example, number_of_decimal(x) would give 11, since the input is unknown at run-time so I can't use setprecision().

我想我应该把问题改成:
如何转换double到不截断浮点的字符串。即

I think I should change my question to: How to convert a double to a string without truncating the floating points. i.e.

#include <iostream>
#include <string>
#include <sstream>

template<typename T>
std::string type_to_string( T data ) {
    std::ostringstream o;
    o << data;
    return o.str();
}

int main() {
    double x = 7.40200;
    std::cout << type_to_string( x ) << "\n";
}

预期输出应为7.40200,但实际结果为7.402。那么我该如何解决这个问题呢?任何想法?

The expected output should be 7.40200 but the actual result was 7.402. So how can I work around this problem? Any idea?

推荐答案

由于 float c $ c> double 内部存储为二进制,文本 7.40200133400 实际代表数字7.40200133400000037653398976544849574565887451171875

Due to the fact the float and double are internally stored in binary, the literal 7.40200133400 actually stands for the number 7.40200133400000037653398976544849574565887451171875

...那么你真正想要多少精度? : - )

...so how much precision do you really want? :-)

#include <iomanip>    
int main()
{
    double x = 7.40200133400;
    std::cout << std::setprecision(51) << x << "\n";
}

是的,这个程序真的打印了7.40200133400000037653398976544849574565887451171875!

And yes, this program really prints 7.40200133400000037653398976544849574565887451171875!

这篇关于如何“cout”正确的小数位数的双精度值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆