在四舍五入VS sprintf的基于Unix的系统在Windows上的差异 [英] Rounding differences on Windows vs Unix based system in sprintf

查看:159
本文介绍了在四舍五入VS sprintf的基于Unix的系统在Windows上的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对基于UNIX的系统的sprintf问题不圆了正确的价值。

I have problem on UNIX based systems sprintf does not round up properly value.

例如

double tmp = 88888888888885.875
char out[512];

那88,888,888,888,885.875只是为了眼睛更容易。
我给这些特定的和大的例子,因为它似乎能正常工作在更小的数字。

Thats 88,888,888,888,885.875 just to be easier on eyes. I am giving such specific and big example because it seems it works fine on smaller numbers.

我想在下面的方式来使用它。

I am trying to use it in following way

sprintf(out, "%021.2f", tmp);
printf("out = %s\n", tmp);

在窗口这会导致:

out = 000088888888888885.88

在例如AIX,但显示了在Linux和:

On for example AIX, but shows in Linux as well:

out = 000088888888888885.87

这是怎么回事?
任何想法,以及如何使其行为在Win / Unix的方式相同。

Why is this happening? Any ideas and how to make it behave same way on Win/Unix

感谢

推荐答案

有一个的错误报告与非常类似你这样的问题的glibc。这里的主要结论(以注释46)是双不是15十进制数字,你不应该指望它像工作。

There is a bug report for glibc with a problem very similar to yours. The main conclusion (in comment 46) here is that double is not a 15-decimal-digit number and you should not expect it to work like that.

作为一种变通方法,您可以添加一些小到你的号码,使他们更好地圆。但这种解决方案并不普遍,因为它依赖于一些范围你处理。

As a workaround you can add something small to your numbers to make them round better. But this solution is not general because it depends on number ranges you deal with.

另一个解决方法可以乘以prepare他们四舍五入,然后倒圆(如 2597.625 * 100 = 259762.5 - > 259763 = 2597.63 * 100

Another workaround can be multiplying to prepare them for rounding, then rounding (e.g. 2597.625*100 = 259762.5 -> 259763 = 2597.63*100)

不过,我认为必须有更聪明的解决办法。

However I think there must be smarter workarounds.

这篇关于在四舍五入VS sprintf的基于Unix的系统在Windows上的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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