Javascript教程
JavaScript基础
JavaScript Objects
JavaScript BOM
JavaScript DOM
JavaScript OOP
JavaScript Cookies
JavaScript事件
JavaScript异常
JavaScript常用

JavaScript 两个数字相加的程序

两个数字相加的 JavaScript 程序

在本例中,您将学习如何使用 JavaScript 中的各种方法将两个数字相加并显示它们的和。
要理解此示例,您应该了解以下JavaScript 编程主题:
JavaScript 变量和常量 JavaScript 运算符
我们使用 + 运算符将两个或多个数字相加。

示例 1: 将两个数字相加

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: 将用户输入的两个数字相加

// 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
上述程序要求用户输入两个数字。在这里, 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 中引入的,一些浏览器可能不支持它们。要了解更多信息,请访问 JavaScript 模板文字支持。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4