Value of Variables

I’m creating a calculator, and need to add the values of first and second number. But, when I do so, it combines the numbers. Ex: Not 18, but 99 (9+9)

My code:

let answer = ‘’

switch (mathFactor) {
case ‘+’:
answer = firstNumber + secondNumber;
break;
case ‘-’:
answer = firstNumber - secondNumber;
break;
case ‘*’:
answer = firstNumber * secondNumber;
break;
case ‘/’:
answer = firstNumber / secondNumber;
break;

}

The way you’ve defined answer (using ‘’) it’s expecting it to be a char or string, rather than a numeric value - so it’s using the + operator as it would when concatenating strings.
Try declaring it as zero. You may need to check how firstNumber, secondNumber are set up as well.

Not sure what language you’re in, but instead of using ‘let’ you may be able to declare answer as something like a float, int, etc which would restrict what could be assigned to it.

1 Like