将双指数的便携式打印到C ++ iostream [英] Portable printing of exponent of a double to C++ iostreams

查看:79
本文介绍了将双指数的便携式打印到C ++ iostream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想便携式地将一个双精度值打印到 std :: cout (GCC,clang,MSVC ++),以使输出在所有平台上都相同。

I want to print a double value to std::cout portably (GCC, clang, MSVC++) such that the output is the same on all platforms.

我对指数的格式有疑问。
以下程序

I have a problem with the formatting of the exponent. The following program

#include <iostream>
int main()
{
    std::cout << 0.1e-7 << std::endl;
    return 0;
}

此输出带有GCC:

1e-08

和以下输出使用MSVC

and the following output with MSVC

1e-008

如何使两个输出相同?

很抱歉,如果这是一个愚蠢的问题,但我没有找到答案,所以远。
所有格式似乎都是围绕尾数之前的所有格式进行演变的。

I'm sorry if this is a dumb question but I have not found an answer so far. All formatting seems to evolve around the formatting of everything before the mantissa...

编辑:GCC的输出为 1e- 08 不是 1e-8 (如最初所述),因此它符合

The output of GCC is 1e-08 not 1e-8 (as originally stated) so it is conforming. Sorry for the confusion.

EDIT2:实际上是在Dietmar发表评论后,将尾数重命名为指数。 在Wikipedia上也有关于尾数与有效数的章节。。 p>

Actually renamed "mantissa" to "exponent" following Dietmar's remark. There also is a section on Wikipedia on mantissa vs. significant.

推荐答案

没有操纵器来控制指数的格式(我假设您是指指数而不是尾数;而且,官方用于尾数的名称是 significant )。更糟的是,我在C标准中看不到任何限制指数格式的规则。我意识到这是关于C ++的,但是出于格式化细节的目的,C ++标准是指C标准。

There is no manipulator controlling the formatting of the exponent (I assume you mean the exponent rather than the mantissa; also, the "official" name used for the mantissa is significant). To make matters worse, I can't see any rule in the C standard which restricts the formatting of the exponent. I realize that this is about C++ but for the purpose of the formatting details, the C++ standard refers to the C standard.

我知道的唯一方法是使用自己的 std :: num_put< char> 构面,该构面可根据需要设置值的格式。然后将此构面放入 std :: locale 中,这又将 imbue()放入 std :: cout 。可能的实现可以使用默认的 std :: num_put< char> 构面(或 snprintf()不幸的是,可能更简单)来格式化浮点数,然后从指数中去除前导零。

The only approach I'm aware of is to use an own std::num_put<char> facet which formats the values as desired. This facet would then be put into a std::locale which in turn is imbue()ed into std::cout. A potential implementation could use the default std::num_put<char> facet (or snprintf() which is, unfortunately, probably simpler) to format the floating point number and then strip leading zeros from the exponent.

这篇关于将双指数的便携式打印到C ++ iostream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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