我被模拟试卷中的这个问题困住了。我需要将“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/