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

标签 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);
    }

}

最佳答案

您的 while 循环条件有问题。

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

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

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

关于Java - 使用 while 循环来解决计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924546/

相关文章:

python - python中的while语句

java - 使用对话框时如何在switch语句中添加while循环?

java - 如何记录整数数组并打印重复项的频率

Javafx 在哪里将标签绑定(bind)到 StringProperty

Java读取文件内的文本

php - 运行过滤器时的查询不正确 - 查询未执行

java - JSONArray 数据不会显示在 Fragment 上

java - 未显示货架选项卡时如何恢复 Intellij 中搁置的更改?

java - while循环和线程的无限循环问题

c++ - 完全数程序中的逻辑错误