【问题标题】:_wtof accuracy isn't all zeros even when string is one decimal accuracy即使字符串是小数点后一位精度,_wtof 精度也不全为零
【发布时间】:2014-07-11 12:37:52
【问题描述】:

使用 _wtof 时,小数点右侧没有一位有效数字。这是我的代码:

DOUBLE fVersion = 0.0;  // Initialize to zero; confirmed fVersion is 0.00000000000000000    
TCHAR sVersion[64] = {0};
_tcscpy_s(sVersion,64,L"1.1");
fVersion = _wtof(sVersion);

使用 _wtof 后 fVersion 为 1.1000000000000001,而不是 1.1。

谁能解释为什么?但最重要的是,如何修复它只是 1.1?

【问题讨论】:

标签: c type-conversion


【解决方案1】:

您无法用二进制浮点数准确表示 1/10(十进制)。因此,会出现错误。

考虑用十进制浮点数表示 1/3,你最终会得到 0.3333333... 它只会永远持续下去,因为这也不可能。

典型的推荐阅读是What Every Computer Scientist Should Know About Floating-Point Arithmetic。真的很不错,看一看。

【讨论】:

  • 我不是在说重复小数,只是一个单精度小数。
  • @JeffR:十进制的 0.1 是二进制的 0.00011001100110011...。阅读提供的链接 unwind。
猜你喜欢
  • 2018-12-24
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多