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 模板字面量 支持。

在结束之前,让我们来测试一下您对 JavaScript 程序相加两个数字的了解!您能解决下面的挑战吗?

挑战

编写一个函数来添加两个数字。

  • 返回 num1num2 的和。
  • 例如,如果 num1 = 4num2 = 5,预期的输出是 9
你觉得这篇文章有帮助吗?

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

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

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