java中的Math.pow()

时间:2016-04-18 00:26:18

标签: java

我的代码有效但仅当您输入的数字高于最后一个时。输入1000即可获得正确的答案,但输入500后会得到相同的答案。知道我做错了吗?

while (number > 0) {
    while (nCubed < number) {
        n++;
        nCubed = (int) (Math.pow(n, 3));
    }

    System.out.println("Results: " + (n - 1) + "^3 < " + number);
    System.out.print("Enter a positive integer (input ends with 0): ");
    number = input.nextInt();
}
System.out.print("End of run");

1 个答案:

答案 0 :(得分:2)

每次循环后,您必须重置nCubedn的值

while (number > 0) {
    n = 0;
    nCubed = 0;
    while (nCubed < number) {
        n++;
        nCubed = (int) (Math.pow(n, 3));
    }

    System.out.println("Results: " + (n - 1) + "^3 < " + number);
    System.out.print("Enter a positive integer (input ends with 0): ");
    number = input.nextInt();
}
System.out.print("End of run");