二次方程式を解くためのJavascriptプログラム

Javascript

このプログラムは、係数がわかっている場合に2次方程式の根を計算します。

二次方程式の標準形式は次のとおりです。

ax2 + bx + c = 0, where
a, b and c are real numbers and
a ≠ 0

このような方程式の根を見つけるために、次の式を使用します。

(root1,root2) = (-b ± √b2-4ac)/2

用語 b2-4ac として知られています 判別式 二次方程式の。 それは根の性質を伝えます。

  1. 判別式がより大きい場合 0、ルーツは リアル そして 異なる
  2. 判別式が等しい場合 0、ルーツは リアル そして 等しい
  3. 判別式が以下の場合 0、ルーツは 繁雑 そして 異なる
二次方程式の根の性質
二次方程式の根の性質

例:二次方程式の根

// program to solve quadratic equation
let root1, root2;

// take input from the user
let a = prompt("Enter the first number: ");
let b = prompt("Enter the second number: ");
let c = prompt("Enter the third number: ");

// calculate discriminant
let discriminant = b * b - 4 * a * c;

// condition for real and different roots
if (discriminant > 0) {
    root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
    root2 = (-b - Math.sqrt(discriminant)) / (2 * a);

    // result
    console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}

// condition for real and equal roots
else if (discriminant == 0) {
    root1 = root2 = -b / (2 * a);

    // result
    console.log(`The roots of quadratic equation are ${root1} and ${root2}`);
}

// if roots are not real
else {
    let realPart = (-b / (2 * a)).toFixed(2);
    let imagPart = (Math.sqrt(-discriminant) / (2 * a)).toFixed(2);

    // result
    console.log(
    `The roots of quadratic equation are ${realPart} + ${imagPart}i and ${realPart} - ${imagPart}i`
  );
}

出力1

Enter the first number: 1
Enter the second number: 6
Enter the third number: 5
The roots of quadratic equation are -1 and -5

上記の入力値は最初の if 状態。 ここでは、判別式は 0 対応するコードが実行されます。

出力2

Enter the first number: 1
Enter the second number: -6
Enter the third number: 9
The roots of quadratic equation are 3 and 3

上記の入力値は、 else if 状態。 ここで、判別式はに等しくなります 0 対応するコードが実行されます。

出力3

Enter the first number: 1
Enter the second number: -3
Enter the third number: 10
The roots of quadratic equation are 1.50 + 2.78i and 1.50 - 2.78i

上記の出力では、判別式は以下になります 0 対応するコードが実行されます。

上記のプログラムでは、 Math.sqrt() メソッドは、数値の平方根を見つけるために使用されます。 あなたはそれを見ることができます toFixed(2) プログラムでも使用されます。 これにより、10進数が2つの10進数値に切り上げられます。

上記のプログラムは if...else ステートメント。 あなたがについてもっと知りたいなら if...else ステートメント、JavaScript if … elseステートメントに移動します。




Hope this helps!

Source link

コメントを残す

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