Java if语句的循环中出错,但编译并终止时没有显示预期结果

Java if语句的循环中出错,但编译并终止时没有显示预期结果,java,if-statement,Java,If Statement,在解决问题时(作为注释出现在代码中),if语句(显示结果)不起作用。请帮我找出错误。它被编译并运行,但输出不显示 /* * (Calculating the Value of π ) Calculate the value of π from the infinite series 4 4 4 4 4 π = 4 – --- + --- – --- + --- – ------ + ... 3 5 7

在解决问题时(作为注释出现在代码中),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;
            }
        }
    }
}
/*
*(计算π的值)从无穷级数中计算π的值
4     4     4     4      4
π = 4 – --- + --- – --- + --- – ------ + ...
3     5     7     9      11
打印一个表格,显示通过计算此参数的前200000项近似得出的π值
系列在首次获得以3.14159开头的值之前,必须使用多少术语?
*/
公共阶级价值观
{
公共静态void main(字符串[]args)
{
int i,计数=0;
双pi=0.0,n=1.0,pi=3.14159;

对于(i=0;i,if语句不起作用的原因是您正在比较浮点数是否相等。本页解释了原因


在重读OP的问题之后,对于这种情况,我首先将pi的计算值转换为一个8个或更多字符长的字符串,并将前7个字符与“3.14159”进行比较。

第一个浮点是inprecise-两个(负)幂和的近似值-(也是3.14159),并且计算的
pi
可以高于或低于给定值

也可以使用
%n
,因为
\n
是Linux行结束,而不是Windows的
\r\n
。这可能会阻止将行缓冲区刷新到输出。(不确定,我有Linux)

if(数学abs(pi-pi)<1.0E-5)
{
System.out.printf(“术语=%d PI=%f%n”,计数,PI);
打破
}
此外,您还可以使用
Math.PI
来获得更好的近似值。您现在有可能获得比
PI
更精确的
PI
,需要0.00001的不精确性


使用==或太小的eps边距(如0.00000001)可能会导致几乎无限的循环。

谢谢,但它不起作用,因为每次加或减(4/n)的pi值增加或减少饼图的值。例如,前10个计数给出的值为4.000000、2.666667、3.466667、2.895238、3.339683、2.976046、3.283738、3.017072、3.252366、3.041840。这些值不是按升序或降序排列的。请尝试
if(Math.abs(pi-pi)<0.000005)
        if (Math.abs(pi - PI) < 1.0E-5)
        {
            System.out.printf("terms=%d     PI=%f%n",count,pi);
            break;
        }