[求助]CodeBlocks开发环境中float变量误差问题

sunshengx 2011-12-14 04:42:14
我用CodeBlocks 进行gcc开发
一下是一个简单例子,我发现监视窗口中的值有误差,见下

float testFF= 0.1234f;
float testGG= 0.1235f;
float testHH= testFF + testGG;
printf("\n the test is %f",testFF);
printf("\n the test is %f",testGG);
printf("\n the test is %f",testHH);



在监视窗口中看到的结果是:
[size=14px]
testFF = 0.123400003
testGG = 0.123499997
testHH = 0.246899992[size=14px]

[size=14px]我换了一种环境:DEC -C++
发现也是同样现象
跪求高手们指导啊
...全文
191 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunshengx 2011-12-15
  • 打赏
  • 举报
回复
(Watch)监视窗口的内容是不准确的吗?
柯本 2011-12-15
  • 打赏
  • 举报
回复
这个是正常的,与编译器无关,浮点数在计算机上的存储本身就是个近似值,这个,参考下:
http://zh.wikipedia.org/zh/IEEE_754
sunshengx 2011-12-15
  • 打赏
  • 举报
回复
我又有测试例子:
float fTest1= 0.1234567891f;
printf("\nthe pointer dTest1 g is %g", fTest1);
printf("\nthe pointer dTest1 f is %12.10f", fTest1);



输出结果是:
the pointer dTest1 g is 0.123457
the pointer dTest1 f is 0.1234567910

请高手再帮我解释一下 谢谢!
sunshengx 2011-12-15
  • 打赏
  • 举报
回复
我又有测试例子:
float fTest1= 0.1234567891f;
printf("\nthe pointer dTest1 g is %g", fTest1);
printf("\nthe pointer dTest1 f is %12.10f", fTest1);



输出结果是:
the pointer dTest1 g is 0.123457
the pointer dTest1 f is 0.1234567910


请高手再帮我解释一下 谢谢!
赵4老师 2011-12-14
  • 打赏
  • 举报
回复
不要管监视窗口的内容,看printf的输出。
赵4老师 2011-12-14
  • 打赏
  • 举报
回复
将%f改为%.6g看看输出什么?
如果换double的话用%.15lg
赵4老师 2011-12-14
  • 打赏
  • 举报
回复
用10进制小数不能精确表示某些三进制小数0.1(3)=0.33333333333……(10)
同理,用二进制小数也不能精确表示某些10进制小数。

参考C:\Program Files\Microsoft Visual Studio 8\VC\include\float.h
...
#define DBL_DIG 15 /* # of decimal digits of precision */
#define DBL_EPSILON 2.2204460492503131e-016 /* smallest such that 1.0+DBL_EPSILON != 1.0 */
#define DBL_MANT_DIG 53 /* # of bits in mantissa */
#define DBL_MAX 1.7976931348623158e+308 /* max value */
#define DBL_MAX_10_EXP 308 /* max decimal exponent */
#define DBL_MAX_EXP 1024 /* max binary exponent */
#define DBL_MIN 2.2250738585072014e-308 /* min positive value */
#define DBL_MIN_10_EXP (-307) /* min decimal exponent */
#define DBL_MIN_EXP (-1021) /* min binary exponent */
#define _DBL_RADIX 2 /* exponent radix */
#define _DBL_ROUNDS 1 /* addition rounding: near */

#define FLT_DIG 6 /* # of decimal digits of precision */
#define FLT_EPSILON 1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON != 1.0 */
#define FLT_GUARD 0
#define FLT_MANT_DIG 24 /* # of bits in mantissa */
#define FLT_MAX 3.402823466e+38F /* max value */
#define FLT_MAX_10_EXP 38 /* max decimal exponent */
#define FLT_MAX_EXP 128 /* max binary exponent */
#define FLT_MIN 1.175494351e-38F /* min positive value */
#define FLT_MIN_10_EXP (-37) /* min decimal exponent */
#define FLT_MIN_EXP (-125) /* min binary exponent */
#define FLT_NORMALIZE 0
#define FLT_RADIX 2 /* exponent radix */
#define FLT_ROUNDS 1 /* addition rounding: near */
...

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧