Question

I am trying to make a javascript program that calculates the area of a trapezoid. So far below is my js code:

var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
    var tr1=prompt("Enter the top base.")
    var tr2=prompt("Enter the bottom base.")
    var tr3=prompt("Now enter the height.")
    confirm((tr1+tr2)*(tr3)/2)
}

But when I put 4,5,6 in my calculator, it spits out 135 instead of 27.

Why?

Was it helpful?

Solution

You can use parseInt to set the values as integers.

var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
    var tr1=Number(prompt("Enter the top base."))
    var tr2=Number(prompt("Enter the bottom base."))
    var tr3=Number(prompt("Now enter the height."))
    confirm((tr1+tr2)*(tr3)/2)
}

Here's a JSFiddle with Benjamine's Number point

http://jsfiddle.net/cXWnk/

OTHER TIPS

The values you are getting back from the prompt are strings and, as Ryan P says, "1" + "1" = "11".

What you need to do is cast the strings to integers before using their values in the calculation.

You can do this with the Number() function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

So, your code might be:

confirm((Number(tr1) + Number(tr2)) *(Number(tr3))/2)

or, using the unary plus shorthand:

confirm((+tr1 + +tr2)*(+tr3)/2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top