mardi 3 septembre 2019

Calculator function based on passed in arguments

I am building a simple calculator as homework. The function takes two numbers (number1, number2) and an operator (+, -, *, /) as argument.

However there are several scenarios:

  1. If the operator is missing --> return "wrong data provided"
  2. If not, then calculate normally
  3. If number 2 is missing --> assume number "0" for + & - calculation and "1" for * & / calculation

This is what I tried

function calc (number1, number2, operator) {
    if (operator == undefined) {
        return "wrong data provided"
    } else {
        if (operator == "+") {
            return number1+number2
        } else if (operator == "-") {
            return number1-number2
        } else if (operator == "*") {
            return number1*number2
        } else if (operator == "/") {
            return number1/number2
        }
    } 

    if (number2 == undefined) {
        if (operator == "+") {
                number2=0;
            return number1+number2
        } else if (operator == "-") {
                number2=0;
            return number1-number2
        } else if (operator == "*") {
            number2=1;
            return number1*number2
        } else if (operator == "/") {
            number2=1;
            return number1/number2
        }
    }  else {
        if (operator == "+") {
            return number1+number2
        } else if (operator == "-") {
            return number1-number2
        } else if (operator == "*") {
            return number1*number2
        } else if (operator == "/") {
            return number1/number2
        }
    } 
}

calc(50,"+") leads to "wrong data provided. Why?

Aucun commentaire:

Enregistrer un commentaire