- 论坛徽章:
- 0
|
请问x是float类型,什么情况下x!=x为真
请看这一例(WIN2000+VC6.0):
- /***********************************************
- *file name : float_accuracy.c
- *description : x是float类型,什么情况下x!=x为真
- *note : 若在判断x!=x前对x进行了修改,则
- 有可能使x!=x为真
- *author : kernelxu
- *resource : http://bbs.chinaunix.net/forum/
- viewtopic.php?t=575049&show_type=
- *date : 2005/07/10
- ***********************************************/
- #include <stdio.h>;
- /**********************************************
- *function name : main()
- ***********************************************/
- int main(void)
- {
- float x = (float)1e-3;
- x = x + 1;
- if (x != x)
- {
- printf("x is UNequal to x!!\n");
- }
- else
- {
- printf("x is equal to x!\n");
- }
-
- return 0;
- }/*END OF main()*/
复制代码
结果:
x is UNequal to x!!
在x!=x判断前对x进行了加法运算,x!=x为真
———————————————————————————————————
第二例
- /***********************************************
- *file name : float_accuracy.c
- *description : x是float类型,什么情况下x!=x为真
- *note : 若在判断x!=x前对x进行了修改,
- 则有可能使x!=x为真
- *author : kernelxu
- *resource : http://bbs.chinaunix.net/forum/
- viewtopic.php?t=575049&show_type=
- *date : 2005/07/10
- ***********************************************/
- #include <stdio.h>;
- /**********************************************
- *function name : main()
- ***********************************************/
- int main(void)
- {
- float x = (float)1e-3;
- x = (float)((int)x + 1);
- if (x != x)
- {
- printf("x is UNequal to x!!\n");
-
- }
- else
- {
- printf("x is equal to x!\n");
- }
-
- return 0;
- }/*END OF main()*/
复制代码
结果:
x=0.001000
x is equal to x!
在x!=x判断前对x进行了又一种加法运算,x!=x为假
——————————————————————————————————
查看相应汇编代码:
第一例:
x = x + 1;
0040E9DF fld dword ptr [ebp-4]
0040E9E2 fadd dword ptr [string "x = %f\n" (00425000)]
0040E9E8 fst dword ptr [ebp-4]
第二例:
x = (float)((int)x + 1);
0040E9DF fld dword ptr [ebp-4]
0040E9E2 call __ftol (0040ea2c)
0040E9E7 add eax,1
0040E9EA mov dword ptr [ebp-8],eax
0040E9ED fild dword ptr [ebp-8]
0040E9F0 fst dword ptr [ebp-4]
两种修改的区别就在于:
第一例是做的double型加法;第二例做的是整型加法。double型运算存在误差,且对double型数据进行关系运算本身就存在误差。 |
|