JavaScript查找数字阶乘的程序

要理解此示例,您应了解以下 JavaScript 编程 主题


一个数字的阶乘是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.

在上面的程序中,会提示用户输入一个整数。然后使用if...else if...else语句检查数字的条件。

  • 当用户输入一个负数时,会显示错误消息。
  • 当用户输入0时,阶乘为1
  • 当用户输入一个正整数时,使用for循环迭代从1到用户输入的数字,以查找阶乘。
  • 每个数字都会相乘并存储在fact变量中。

在结束之前,让我们通过以下挑战来测试您对 JavaScript 查找数字阶乘程序的知识!您能解决以下挑战吗?

挑战

编写一个函数来计算一个数字的阶乘。

  • 非负整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。
  • 例如,3 的阶乘是 3 * 2 * 1 = 6
  • 返回输入数字 num 的阶乘。
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战