咨询:如何实现递归阶乘函数计算过程与结果同步展示?
Solution to Show Factorial Calculation Process
Got it, let's adjust your factorial function to display the full calculation process along with the result! Your original code gets the right answer, but we just need to add a bit of logic to track the multiplication string as we go.
Modified Code
function factorial(n) { // Handle edge cases for 0! and 1! if (n === 0 || n === 1) { alert(`${n}! = 1`); return; } let result = n; let calculationStr = `${n}`; // Loop from n-1 down to 1 to build the correct multiplication sequence for (let i = n - 1; i >= 1; i--) { result *= i; calculationStr += ` * ${i}`; } // Show the full process and result alert(`${calculationStr} = ${result}`); } // Test with input 5 factorial(5); // Alerts "5 * 4 * 3 * 2 * 1 = 120"
Key Changes Explained
- Edge Case Handling: We added checks for
n=0andn=1since their factorials are both 1, and we can display a clear message for these cases too. - Calculation String Tracking: We initialize
calculationStrwith the input number, then append each subsequent multiplier (n-1,n-2, ...,1) to the string during each loop iteration. - Loop Adjustment: Instead of counting up from 1, we count down from
n-1—this makes it easy to build the multiplication sequence in the intuitive "5 * 4 * 3 * 2 * 1" order, matching what you want to display.
If you prefer to log to the console instead of using an alert, just swap out the alert() calls with console.log()—the core logic stays identical.
内容的提问来源于stack exchange,提问作者Bumblejr2
相关产品推荐
相关产品推荐

