数の階乗を見つける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 変数。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です