gcc double printf precision - 错误的输出 [英] gcc double printf precision - wrong output

查看:171
本文介绍了gcc double printf precision - 错误的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< stdio.h> 
#include< wchar.h>
int main()
{
double f = 1717.1800000000001;
wprintf(Ldouble%.20G \\\
,f);
返回0;




$ b $ p

输出(和预期的下面):

  double 1717.1800000000000637 
double 1717.1800000000001



<这是在Ubuntu 11.10 x64上(也是在编译32位时)。

我试图解决的问题是在Windows上输出数字像在代码中一样,我需要使低级格式化(swprintf)像在Windows中一样工作,以实现可移植性问题。 解决方案

1717.1800000000001并不能完全表示为double,所以在f中你只能得到一个值。存储在f中的值恰好是1717.180000000000063664629124104976654052734375。现在的问题是,Windows只输出17位有效数字,虽然有20位被请求(这是一个已知的错误,AFAIK它的错误数据库中的某处)。

如果您不能将字段长度限制为合理的值(如%。17G),你需要一个包装来模仿这个bug。


#include <stdio.h>
#include <wchar.h> 
int main()
{
    double f = 1717.1800000000001;
    wprintf(L"double      %.20G\n", f);
    return 0;
}

outputs (and expected below):

double      1717.1800000000000637
double      1717.1800000000001

This is on Ubuntu 11.10 x64 (but also when compiling for 32 bit).

The problem that I try to solve, is that on Windows it outputs the number exactly like in code, and I need to make low-level formatting (swprintf) to work like in Windows, for portability issues.

解决方案

1717.1800000000001 is not exactly representable as double, so you only get a value near to it in f. The value stored in f is exactly 1717.180000000000063664629124104976654052734375.

The problem is now that windows does only output 17 significant digits, although 20 were requested (which is a known bug, AFAIK it's somewhere in their bug database).

If you can't limit the field length to a sane value (like "%.17G"), you need a wrapper to mimic this bug.

这篇关于gcc double printf precision - 错误的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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