This forum is now read-only. Please use our new forums! Go to forums
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
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.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency