我对过去试卷上的一道题有困难。我想把一个 from
数字到a n
号码。换句话说:from*(from+1)(from+2).*n。
我需要使用while循环来解决这个问题。到目前为止,我已经这样做了,不知道该怎么办。我知道密码是错的,但已经卡住了一段时间。
public class Fact {
public int last;
private int factPartND(final int from, final int n) {
int fromNum = from;
int toNum = n;
int result = 1;
int c = 1;
while (fromNum <= toNum) { // e.g.5*6*7*8*9*10*11
result = (fromNum) * (fromNum + c); // calculate 5*6
final int temp = result; // store 5*6
int result1 = temp * (fromNum + c); // store 5*6*7*....
c++; // increments the fromNum in the while code
fromNum++; // increments 5 to 11 in the while condition
last = result1;
}
return last;
}
public static void main(String[] args) {
Fact f = new Fact();
System.out.println(test);
}
}
6条答案
按热度按时间crcmnpdw1#
我将尝试更广泛地回答这个问题,而不仅仅是关注你的问题
while
循环。请注意以下评论:考虑一下,与其编写语句函数来执行某些操作,不如编写返回内容的表达式。
注意,这个解决方案基本上是三行长的。它利用了一个事实,即你的问题分解成一个稍微小的问题。它还可以优雅地处理边缘案例(以及对预期结果的评论)。
同样要注意的是,这种方法(一种“递归”方法)会对性能产生影响,但过早优化是万恶之源,正如第一次尝试时会出现清晰度问题一样。
llmtgqce2#
一些伪代码:
y1aodyip3#
我认为这个应该作为while循环
hfsqlsce4#
快试试这个。。希望有帮助:-)
bwleehnv5#
以下是您的中心方法的简单版本:
如果你移除了
final
上的修饰符from
参数,则可以消除局部变量f
:很简单!
velaa5lx6#
严格地
while
: