一个数的阶乘是从 1 到该数的所有数的乘积。例如,
5 的阶乘等于 1 * 2 * 3 * 4 * 5 = 120。
正数n的阶乘由下式给出:
factorial of n (n!) = 1 * 2 * 3 * 4.....n
负数的阶乘不存在,0的阶乘是1。
示例: 求因子
// program to find the factorial of a number // take input from the user const number = parseInt(prompt('Enter a positive integer: ')); // checking if number is negative if (number < 0) { console.log('Error! Factorial for negative number does not exist.'); } // if number is 0 else if (number === 0) { console.log(`The factorial of ${number} is 1.`); } // if number is positive else { let fact = 1; for (i = 1; i <= number; i++) { fact *= i; } console.log(`The factorial of ${number} is ${fact}.`); }
输出
Enter a positive integer: 5 The factorial of 5 is 120.
在上面的程序中,提示用户输入一个整数。然后
当用户输入负数字时,会显示一条错误消息。
当用户输入0时,阶乘为1。
当用户输入一个正整数时,if...else if...else
语句用于检查一个数的条件。
for
循环用于遍历 1 到用户输入的数字以找到阶乘。
每个数字相乘并存储在 fact
变量中。