+ 2
Javascript function doesn't add a variable to a number for some reason!
I wrote this function that displays the opposite magnetic heading in degrees. But instead of completing the addition it instead just add these two together as if they were strings. function opp_head(x){ if(x<180){ x += 180; return x; } else { x -= 180; return x; } } let x = prompt("Enter your heading to get the opposite here!"); console.log(opp_head(x) + " is the opposite heading.");
5 Answers
+ 2
Cast to a numeric type before using the x with parseInt(). After that you can use it as a number:
let x = parseInt(prompt("Enter your heading to get the opposite here!"));
Also, with ECMASCRIPT 6 you can do interpolation using backticks to print your answer, it's something like this:
console.log(`${opp_head(x)} is the opoosite heading.`)
+ 2
parseInt(x) before passing x to the function will make x a number
0
You need to convert the value of x to a number before adding 180 to it. You can do this using the Number() function.
0
function opp_head(x){
x = Number(x);
if(x<180){
x += 180;
return x;
} else {
x -= 180;
return x;
}
}
let x = prompt("Enter your heading to get the opposite here!");
console.log(opp_head(x) + " is the opposite heading.");
0
Add a parseFloat(x) instead of Number (x) or parseInt(x) and if you are also getting your values from an input tag use . valueAsNumber instead of.value