作者sjgau (sjgau)
看板Programming
标题Re: [问题] 基本程式设计概念的问题
时间Mon Jan 21 11:19:33 2008
底下,我用 Dev-C++ 实作,得到的结果和 您的构想不同。
当然啦!我不会否定 您的想法,我只是想说明一件事,
程式设计这种东西,一定要实际做过一遍,才能拿来说嘴。
否则,很容易得到不同的结果。
我很清楚怎麽 一回事情,这种东西讨论起来,
没完没了。
/*
a= 1.000000
请按任意键继续 . . .
a= 0.333333
请按任意键继续 . . .
a= 1.000000
请按任意键继续 . . .
Yes! a == 1.0
请按任意键继续 . . .
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
float a;
a= 1.0;
printf("a= %f\n", a);
system("PAUSE");
a/= 3.0;
printf("a= %f\n", a);
system("PAUSE");
a*= 3.0;
printf("a= %f\n", a);
system("PAUSE");
if (a == 1.0) {
printf("Yes! a == 1.0\n");
}
else {
printf("No! a <> 1.0\n");
}
system("PAUSE");
return 0;
}// end of main()
※ 引述《yzugsr (Bird)》之铭言:
: ※ 引述《trickli (哲)》之铭言:
: : (1) Rewrite the following pseudo-code if statement expression
: : in a more realistic manner assuming that variables a and b are
: : of type real:
: : if (a = b) then
: : ....
: threshold = 0.00001 # 误差容许值
: if (a > b - threshold) and (a < b + threshold)
: : (2) Explain why this is necessary.
: : 这题好像是关於两个实数不太可能相等的问题,但不知道该怎麽作答。
: : 这是澳洲某大学 2006 年期末考题,请各位高手帮忙。
: : 谢谢。
: 因为浮点数有精确度的限制
: float a = 1;
: a /= 3;
: a *= 3;
: if (a==1) print "Yes"; else print "No";
: 你应该会得到No的答案
: 因为执行完第二行时 a的数值应该是1/3 写成十进位是0.3333333333....
: 电脑是用二进位记符点数的,而且有位数的限制
: 应该会变成0.0101010101.....循环
: 执行完第三行 a*=3 就变成0.999999999999999999998之类的东西
: 最後这个数就小於一了
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 211.77.241.2