2つの数字を追加するJavaScriptプログラム

Javascript

私たちは使用します + 2つ以上の数値を加算する演算子。

例1:2つの数値を追加する

const num1 = 5;
const num2 = 3;

// add two numbers
const sum = num1 + num2;

// display the sum
console.log('The sum of ' + num1 + ' and ' + num2 + ' is: ' + sum);

出力

The sum of 5 and 3 is: 8

例2:ユーザーが入力した2つの数字を追加する

// store input numbers
const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));

//add two numbers
const sum = num1 + num2;

// display the sum
console.log(`The sum of ${num1} and ${num2} is ${sum}`);

出力

Enter the first number 5
Enter the second number 3
The sum of 5 and 3 is: 8

上記のプログラムは、ユーザーに2つの数字を入力するように求めます。 ここに、 prompt() ユーザーからの入力を取得するために使用されます。 parseInt() ユーザー入力文字列を数値に変換するために使用されます。

const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));

次に、数値の合計が計算されます。

const sum = num1 + num2;

最後に、合計が表示されます。 結果を表示するために、テンプレートリテラルを使用しました ` `。 これにより、文字列内に変数を含めることができます。

console.log(`The sum of ${num1} and ${num2} is ${sum}`);

内部に変数を含めるには ``、を使用する必要があります ${variable} フォーマット。

注意:テンプレートリテラルはES6で導入され、一部のブラウザはそれらをサポートしていない可能性があります。 詳細については、次のWebサイトをご覧ください。 JavaScriptテンプレートリテラル サポート。



Hope this helps!

Source link

コメントを残す

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