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);
}
}
このソリューションは、本質的に 3 行の長さに注意してください。問題がわずかに小さな問題に分解されるという事実を利用しています。また、エッジケースを適切に処理します (および期待される結果についてコメントします)。
また、この方法 (「再帰的」方法) にはパフォーマンスへの影響があることにも注意してください。ただし、最初の試行で明確性の問題が発生するのと同様に、時期尚早の最適化がすべての悪の根源であることにも注意してください。