如何“cout”正确的小数位数的双精度值?

编程入门 行业动态 更新时间:2024-10-23 03:23:55
本文介绍了如何“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”正确的小数位数的双精度值?

本文发布于:2023-11-23 01:32:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619632.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小数   位数   精度   正确   cout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!