簡單的 JavaScript 計算器
Muhammad Muzammil Hussain
2023年1月30日
2022年5月10日
本文將讓你瞭解如何在 JavaScript 上使用多種方式開發一個簡單的計算器。要理解這一點,你必須瞭解以下 JavaScript 條件:
- JavaScript
If else if
語句 - JavaScript
switch
語句
JavaScript 計算器
我們在日常生活中使用計算器來執行許多數學運算,例如加法、減法、乘法。
我們還可以使用科學計算器來解決複雜問題,例如平方根和對數函式。
JavaScript 是構建用於新增網頁的計算器的最常用和首選語言。
在 JavaScript 中使用 if-else if
語句構建計算器
<html>
<head>
<title>
JavaScript calculator using If Else If
</title>
</head>
<script>
// getting number-1 from user
var no1 = parseFloat(prompt("Please Enter your 1st No. : "));
// getting operator to perform operation on two numbers
var operator = prompt("Enter operator ( either +, -, * or / ) : ");
// getting number-2 from user
var no2 = parseFloat(prompt("Please Enter your 2nd No. : "));
var result;
// using if else if to perform operation according to the operator
if (operator == "+")
{
result = no1 + no2; // to add two numbers
}
else if (operator == "-")
{
result = no1 - no2; // to subtract two numbers
}
else if (operator == "*")
{
result = no1 * no2; // to multiple two numbers
}
else
{
result = no1 / no2; // to divide two numbers
}
// Displaying the result
window.alert("Required result is : " + result);
</script>
<body>
<h2 style="text-align: center">Thats practical demo about JavaScript
calculator using JavaScript If Else If</h2>
<body>
</html>
輸出:
Please Enter your 1st No. : 12
Enter operator ( either +, -, * or / ) : +
Please Enter your 2nd No. : 13
Required result is : 25
That's a practical demo about JavaScript calculators using JavaScript. If Else If
在 JavaScript 中使用 switch
語句構建計算器
<html>
<head>
<title>
JavaScript calculator using switch statement
</title>
</head>
<script>
// getting number-1 from user
var no1 = parseFloat(prompt("Please Enter your 1st No. : "));
// getting operator to perform operation on two numbers
var operator = prompt("Enter operator ( either +, -, * or / ) : ");
// getting number-2 from user
var no2 = parseFloat(prompt("Please Enter your 2nd No. : "));
var result;
// using switch statement to operate according to the operator
switch(operator)
{
case "+":
result = no1 + no2; // adding two numbers
break;
case "-":
result = no1 - no2; // subtracting two numbers
break;
case "*":
result = no1 * no2; // multiplying two numbers
break;
case "/":
result = no1 / no2; // dividing two numbers
break;
default:
console.log('Invalid operator');
break;
}
// Displaying the result
window.alert("Required result is : " + result);
</script>
<body>
<h2 style="text-align: center">Thats practical demo about JavaScript
calculator using JavaScript switch statement</h2>
<body>
</html>
輸出:
Please Enter your 1st No. : 25
Enter operator ( either +, -, * or / ) : /
Please Enter your 2nd No. : 5
Required result is : 5
That's a practical demo about JavaScript calculator using JavaScript switch statement