我将尝试更广泛地回答这个问题,而不仅仅是关注你的while
循环。请注意以下评论:
public class Fact {//I assume, based on your question, you really mean 'Factorial'.
//Examining this for the first time I might assume that this object has to do with
//well-established observations, or 'Facts'. Fight the urge to abbreviate everything.
public int last;//Why is this a member variable of the class?
private int factPartND(final int from, final int n) {
//How are your 'from' and 'n' variables related? It's unclear based on their names.
//The method name is also incomprehensible.
//Why are the parameters declared 'final'?
//Why is this a private method?
//Why is this not a static method?
int fromNum = from;//If you're redeclaring, there is probably a problem.
int toNum = n;
int result = 1;//Is this your default result? You should be notating it in the method
//comments if you're assuming some things, like no negative numbers.
int c = 1;//What is c?
//You have latched on to 'while' as the only way of doing this.
while (fromNum <= toNum) { // e.g.5*6*7*8*9*10*11
result = (fromNum) * (fromNum + c); // calculate 5*6
//And then set result to the result? What about what was in there before?
final int temp = result; // store 5*6
//Why is this int final?
int result1 = temp * (fromNum + c); // store 5*6*7*....
c++; // increments the fromNum in the while code
//Actually increments the adder to what you're multiplying by three lines earlier
fromNum++; // increments 5 to 11 in the while condition
last = result1;
//Your use of temporary variables is way overdone and confusing.
}
return last;
}
public static void main(String[] args) {
Fact f = new Fact();
System.out.println(test);
}
}
考虑一下,而不是编写执行某些操作的 STATEMENTS 函数,您想编写返回事物的 EXPRESSIONS。
public class Factorial {
/**
* Calculates the product of a series of integers from 'start' to 'end'. 'start' must be
* less than or equal to 'end', or it will return 1.
*/
public static factorialRange(int start, int end) {
if (start > end) { return 1; }
if (start = end) { return end; }
return start * factorialRange(start + 1, end);
}
}
请注意,此解决方案本质上是三行长。它利用了这样一个事实,即您的问题分解为一个稍小的问题。它还可以优雅地处理您的边缘情况(并对预期结果进行评论)。
另请注意,此方法(“递归”方法)会影响性能,但过早的优化是万恶之源,就像您的第一次尝试存在清晰度问题一样。