简体   繁体   English

Java循环无限运行

[英]Java loop runs infinite

I am doing a factorial question with java loop, it asks 1+1/2!+1/3!+...+1/n!, n is positive, I am using "while" to make it, but the code is run with nothing : 我在用Java循环做一个阶乘问题,它询问1 + 1/2!+1/3!+ ... + 1 / n!,n为正数,我使用“ while”创建它,但是代码没有任何运行:

    public static void main(String[] args) {

    double sum=0,a=1;
    int n=Integer.parseInt(args[0]);
    while(n>0){

        a=a*n;
        sum=sum+1.0/a;
    }
    System.out.print(sum);

}

please help:) 请帮忙:)

while(n>0){
    a=a*n;
    sum=sum+1.0/a;
}

When do you change n ? 你什么时候换n You don't. 你不知道 The condition will be always satisfied and you'll never exit the loop. 条件将始终得到满足,您将永远不会退出循环。 Consider changing the value of n in the body of the loop. 考虑在循环体内更改n的值。

 Iteration |   n
-----------+--------
     1     |   n      > 0 ? Yes
     2     |   n      > 0 ? Yes
     3     |   n      > 0 ? Yes
    ...    |
    ...    |
  Forever  |   n      > 0 ? Yes

As others have pointed out, your original while loop never ends, because the value of n never changes, meaning that the while condition will always be true (assuming the original value was greater than zero). 正如其他人指出的那样,您的原始while循环永远不会结束,因为n的值不会改变,这意味着while条件将始终为true(假设原始值大于零)。

Is this possibly what you are trying to achieve? 这可能是您想要实现的目标吗?

public static void main(String[] args)
{
    double sum = 0, a = 1;
    int n = Integer.parseInt(args[0]);
    for ( int i = 1; i <= n; i++ )
    {
        a *= i;
        sum = sum + (1.0 / a);
    }
    System.out.print(sum);
}

Your code is equal to : 您的代码等于:

while(true){

    a=a*n;
    sum=sum+1.0/a;
}

You don't change n value , n must be <=0 to break your loop . 你不能改变n值, n必须<=0才能break loop

Why not try a for loop let's say 为什么不尝试一个for循环呢?

public static void main(String[] args) {

    double sum=0;
    int  n=Integer.parseInt(args[0]);
    for(double a=1;a<=n;a++){

        sum=sum+1.0/a;
    }
    System.out.print(sum);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM