This forum is now read-only. Please use our new forums! Go to forums

0 points
over 9 years

Couldn't find any other forum for this

Okay, I’m trying to make a calculator codebit, but this is the sort of thing that makes you want to strangle whoever made ‘+’ the JavaScript concatenation operator instead of something like ‘~’, but I’m rambling here. This is my code:

document.write("Hello, and welcome to the Aperture Science Computer Aided Calculation Program!<br>");
document.write("Initializing user interface...<br>");
function calculate(op) {
  switch(op){
    case "+":
      document.write("Adding " + num0 + " and " + num1 + "...<br>");
      var sum = num0 + num1;
      document.write(sum);
      break;
    case "-":
      document.write("Subtracting " + num1 + " from " + num0 + "...<br>");
      document.write(num0 - num1);
      break;
    default:
      alert("ERROR: OPERATOR is not +, -, *, /, **, or //");
  };
};
document.write("Interface loaded!<br>");
/*var num0 = prompt("Input your first number:", "Number one here");
var num1 = prompt("Input your second number:", "Number two here");
var operate = prompt("Input the operator(+, -, *, /, **, //):", "Operator here");*/
if(isNaN(num0) || isNaN(num1)) {
  alert("ERROR: var num0 or var num1 is not an integer");
} else {
  calculate(operate);
}

Subtraction works fine. When I try to add 55 + 45, though, it spits out: Adding 55 and 45… 5545 It should write: Adding 55 and 45… 100 Note that originally, instead of storing the answer in ‘sum’, the addition was done directly in document.write().

Answer 546188f1631fe961e6000d2a

0 votes

Permalink

I compiled and ran your code in http://labs.codecademy.com/#:workspace, and found the solution for your problem.

So i m just posing the answer for the Addition part:

case “+”: console.log(“Adding “ + num0 + “ and “ + num1 + “…
“); var sum = (+num0) + (+num1); console.log(sum); break;

You can also use Number() like this. var sum = Number(num0) + Number(num1);

I have used console.log(), you can replace it with document.write();

Hope this will answer your question.

points
Submitted by Kavita Tiwari
over 9 years