我會嘗試更廣泛地有所回答這個問題,不是僅僅專注於你的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);
}
}
考慮,而不是寫那些東西,你要編寫返回的東西表達語句的功能。
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);
}
}
請注意,該解決方案本質上是三行。它利用了您的問題分解成稍微小一點的問題。它也優雅地處理您的邊緣案例(並對預期結果進行評論)。
請注意,這種方法會有性能影響(「遞歸」方法),但過早優化是所有惡意的根源,就像您的第一次嘗試存在清晰度問題一樣。
你看起來很複雜這件事。弄清楚如何先在紙上做這件事,然後編碼。簡化。 –
是這個作業嗎? –
我最初嘗試過,但是我無法找到一種不由inital fromNum乘法的方法,因爲我通過每次迭代繼續乘以該數字。 – nsc010