📜  使用JavaScript程序制作简单的计算器

📅  最后修改于: 2020-09-27 05:30:12             🧑  作者: Mango

在此示例中,您将学习编写程序以使用JavaScript制作一个简单的计算器。

示例1:具有if..else if … else的简单计算器
// program for a simple calculator

// take the operator input
let operator = prompt('Enter operator ( either +, -, * or / ): ');

// take the operand input
let number1 = parseFloat(prompt('Enter first number: '));
let number2 = parseFloat(prompt('Enter second number: '));

let result;

// using if...else if... else
if (operator == '+') {
    result = number1 + number2;
}
else if (operator == '-') {
    result = number1 - number2;
}
else if (operator == '*') {
    result = number1 * number2;
}
else {
    result = number1 / number2;
}

// display the result
console.log(`${number1} ${operator} ${number2} = ${result}`);

输出

Enter operator ( either +, -, * or / ): *
Enter first number: 3.4
Enter second number: 5.6
3.4 * 5.6 = 19.04

在上面的示例中,提示用户输入一个运算符 ( +*/)和两个数字。

parseFloat()将数字字符串值转换为浮点值。

if...else if...if语句用于检查用户为运算符输入的条件。执行相应的操作并显示输出。


示例2:带开关的简单计算器
// program for a simple calculator
let result;

// take the operator input
let operator = prompt('Enter operator ( either +, -, * or / ): ');

// take the operand input
let number1 = parseFloat(prompt('Enter first number: '));
let number2 = parseFloat(prompt('Enter second number: '));

switch(operator) {
    case '+':
         result = number1 + number2;
        console.log(`${number1} + ${number2} = ${result}`);
        break;

    case '-':
         result = number1 - number2;
        console.log(`${number1} - ${number2} = ${result}`);
        break;

    case '*':
         result = number1 * number2;
        console.log(`${number1} * ${number2} = ${result}`);
        break;

    case '/':
         result = number1 / number2;
        console.log(`${number1} / ${number2} = ${result}`);
        break;

    default:
        console.log('Invalid operator');
        break;
}

输出

Enter operator: +
Enter first number: 4
Enter second number: 5
4 + 5 = 9

在上述程序中,要求用户输入+*/以及两个数字。然后, switch语句根据用户输入执行案例。