简体   繁体   English

如何做一个简单的计算器

[英]How to do a simple calculator

The task is to implement a function , a simple addition and subtraction calculator that:任务是实现一个函数,一个简单的加法和减法计算器,它:

  • Takes three arguments, two integers, firstArg, SecondArg and a string operation that is either "+" or "-"接受三个参数、两个整数、firstArg、SecondArg 和一个字符串操作,即“+”或“-”
  • Returns a value depending on operation: If operation is + then it returns the sum of the firstArg with the secondArg.根据操作返回一个值:如果操作是 +,则返回 firstArg 与 secondArg 的总和。 If operation is - then ir returns the subtraction of the firstArg with the secondArg.如果操作是 - 则 ir 返回 firstArg 与 secondArg 的减法。 If operation isn't none then it returns "invalid operation"如果操作不是无,则返回“无效操作”

Can someone help?有人可以帮忙吗?

function name(a0, a1, a2) {
  return a2 === "+"? a0 + a1: a0 - a1;
}

Here is the function, as you asked:这是功能,正如您所问:

const calculator = function(firstArg, secondArg, operationType) {
    if (operationType === '+') {
        return firstArg + secondArg;
    } else if (operationType === '-') {
        return firstArg - secondArg;
    }
}

Below is the function as you asked.下面是你问的功能。 The switch statement in JavaScript can be learnt about here . JavaScript 中的 switch 语句可以在这里学习。 If you wanted to use something maybe slightly simpler have a look at the other answers.如果您想使用一些可能稍微简单的东西,请查看其他答案。

function simpleAdditionAndSubtractionCalculator(num1, num2, operatorType) {
    switch(operatorType) {
        case "-":
            return num1 - num2;
            break;
        case "+":
            return num1 + num2;
            break;
        default:
            return "Invalid operation!";
            break;
    }
}

 function process (operation, a, b) { if(operation === '+'){ return a + b; }else if(operation === '-'){ return a - b; }else{ return "invalid operation"; } } console.log( process('+',3,5) );

You need to use js eval function你需要使用js eval函数

function simpleAdditionAndSubtractionCalculator(num1, num2, operatorType) {
    return eval(num1 + operatorType + num2)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM