1

这是过去试卷中的一道题。问题中给出了代码,我需要获取值以及断点的次数。我曾尝试在 Eclipse 中运行代码,但无济于事。(如果执行代码,我可以在调试模式下找到值)

问题还指出:该方法fact是在值为 6 的类的实例上调用的n。不确定我做错了什么,因为代码与问题中给出的完全相同。

public class FactLoop {

private int n;// assumed to be greater than or equal to 0

/**
 * Calculate factorial of n
 * 
 * @return n!
 */
public int fact() {
    int i = 0;
    int f = 1;

    /**
     * loop invariant 0<=i<=n and f=i!
     */

    while (i < n) {// loop test (breakpoint on this line)
        i = i++;
        f = f * i;
    }
    return f;
}

// this main method is not a part of the given question
public static void main(String[] args) {
    FactLoop fl = new FactLoop();
    fl.n = 6;
    System.out.println(fl.fact());
}

}

4

1 回答 1

8

你的错误在i=i++;. i++增加 i,并返回 i 的旧值。通过说i=i++,您将其递增,然后将其设置为旧值。

只是i++;用来增加它。

于 2012-08-24T15:51:58.703 回答