Java - 使用while循环来解决计算

时间:2012-08-12 18:10:46

标签: java while-loop

我在模拟试卷上坚持这个问题。我需要将'from'数字乘以'n'数字。换句话说:from *(from + 1)(from + 2) ... * n。

我需要使用while循环来解决这个问题。到目前为止我已经这样做了,不知道该怎么做。

class Fact {

    private int factPartND(final int from, final int n) {

        int c = 1;
        int z = from;
        int y = n;
        int num = 0;

        while (y >= z) {

            num += from * (from + c);// need to stop multiplying from for each
                                     // iteration?
            c++;
            y--;
        }

        return num;
    }

    public static void main(String[] args) {
        Fact f = new Fact();
        int test = f.factPartND(5, 11);
        System.out.println(test);
    }

}

4 个答案:

答案 0 :(得分:4)

您的while循环条件存在问题。

while(y>=z)
{
    ....
}

将执行您的代码n + 1次。 即如果你想从5到11执行,这个条件将允许执行到12。

在while循环中更好地使用while(y>z)条件。

答案 1 :(得分:3)

你的计算是:

from * (from + 1) * (from + 2) * ... * (from + n)

将每个因子视为循环的一次迭代。

因此,您的第二次迭代应该将您的累计值乘以(from + 1),然后再乘以(from + i)再乘以from < i < n,依此类推,直到您将累计值乘以{{1 }}

您的代码非常接近 - 您在每次迭代中都有(from + n),但算术错误。

正如已经提到的那样,使用(from + c) c来跟踪你的循环有点令人困惑,只需要测试{{1}就足够了}。

答案 2 :(得分:-2)

public class Fact {

    private int factPartND(final int from, final int n) {
        int m = 1;
        int result = from;

        while (m <= n) {
            result *= (from + m++);
        }

        return result;
    }

    public static void main(String[] args) {
        Fact f = new Fact();
        int test = f.factPartND(5, 8);
        System.out.println(test);
    }
}

如果你用5,11这样做,你就会溢出。那么你应该使用BigInteger而不是int。

答案 3 :(得分:-3)

也许是这样的:

package homework;
public class Homework {

    public static int fact(int from, int to){
    int result = 1;
    while(to>0){
        result*=from+to;
        to--;
    }
    return result*from;
    }
    public static void main(String[] args) {
    System.out.println(fact(2,4));
    }
}