[英]error in loop with if statement, but gets compiled and terminates without error without displaying expected result
解决问题时(在代码中作为注释。)if语句(显示结果)不起作用。 请帮助我找出错误。 它被编译并运行,但未显示输出。
/*
* (Calculating the Value of π ) Calculate the value of π from the infinite series
4 4 4 4 4
π = 4 – --- + --- – --- + --- – ------ + ...
3 5 7 9 11
Print a table that shows the value of π approximated by computing the first 200,000 terms of this
series. How many terms do you have to use before you first get a value that begins with 3.14159?
*/
public class ValueOfPi
{
public static void main(String[] args)
{
int i,count=0;
double pi=0.0,n=1.0,PI=3.14159;
for(i=0;i<200000;i++)
{
count++;
if(count%2!=0)
{
pi=pi+(4/n);
}
else if(count%2==0)
{
pi=pi-(4/n);
}
n=n+2;
if(pi==PI)
{
System.out.printf("terms=%d PI=%f\n",count,pi);
break;
}
}
}
}
if语句不起作用的原因是,您正在比较浮点数是否相等。 每位计算机科学家应该了解的有关浮点运算的页面说明了原因。
在重新阅读了OP的问题之后,对于这种情况,我首先将pi的计算值转换为长度为8个或更多字符的字符串,然后将前7个字符与“ 3.14159”进行比较。
第一个浮点数是不精确的-大约为2的(负)幂的和-(也有3.14159),并且计算出的pi
可以高于或低于给定值。
也将%n
用作\\n
是Linux行末,而不是Windows \\r\\n
。 这可能会阻止刷新行缓冲区以输出。 (不确定,我有Linux)。
if (Math.abs(pi - PI) < 1.0E-5)
{
System.out.printf("terms=%d PI=%f%n",count,pi);
break;
}
另外,您可以使用Math.PI
以获得更好的近似值。 现在,您需要冒比需要0.00001不精确度的PI
更精确的pi
风险。
使用==或太小的eps余量,例如0.00000001可能会导致几乎无限循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.