所以,一位朋友向我分享了這個代碼,並且我很難理解它是如何提供正確的結果的,因爲它沒有經過一個循環。如果有人能像我這樣向我解釋它5我真的很感激它。有人可以向我解釋這段代碼的工作原理嗎?
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
所以,一位朋友向我分享了這個代碼,並且我很難理解它是如何提供正確的結果的,因爲它沒有經過一個循環。如果有人能像我這樣向我解釋它5我真的很感激它。有人可以向我解釋這段代碼的工作原理嗎?
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
在階乘的屬性,n!
可被寫入爲n * (n-1) !
。 也就是說,n的函數的結果可以作爲獲得n倍該函數的結果爲n-1
,等等,以1:
function factorial(n) {
return (n != 1) ? n * factorial(n - 1) : 1;
}
alert(factorial(5)); // 120
遞歸基礎是值1。你可以使基礎和0。然後,代碼會更短一點:
function factorial(n) {
return n ? n * factorial(n - 1) : 1;
}
alert(factorial(5)); // 120
在這種情況下,呼叫factorial (1)
減小到1 * factorial (0)
,會有遞歸的附加步驟。
該代碼是一個遞歸函數調用來獲取數字的階乘。
function fact(n){ // function declaration
if(n === 1){ //strict type check if n is an integer 1 not a '1'
return 1; // return back 1
}else{ // if n is not 1
return n * fact(n - 1); //return the number n multiplied by the function call fact again in which the parameter is n-1 now.
};
};
console.log(fact(5)); //print the result of function call fact(5) and print it to console.
function fact(n){
if(n === 1){
return 1;
}else{
return n * fact(n - 1);
};
};
console.log(fact(5));
它是運行在數學公式的呼叫來計算階乘:
n * (n-1) !
當涉及到遞歸時,你可以把它看作一個調用自己的函數;在這種情況下
function fact(n){
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
console.log(fact(5));
所以當你調用這個案件事實(5) 你會得到 5 *事實(5-1)= 4 *事實(4-1)= 3 *事實(3- 1)= 2 *事實(2-1)= 1
導致5 * 4 * 3 * 2 * 1 = 120
它有點棘手的一個概念,以在第一弄清楚,嘗試插入console.log加入到函數中,讓您更清楚地瞭解發生了什麼。
function fact(n){
console.log(n);
//test to see if n is 1, if so just return 1
if(n === 1)
return 1;
// multiply n by the result of calling fact(n-1)
return n * fact(n - 1);
}
您的Google關鍵字是'recursion' –
它使用循環;它是遞歸的。查找遞歸工作。這*確切*代碼已被解釋過很多次。 – Carcigenicate
你的朋友拒絕向你解釋嗎? – BoltClock