Reputation: 256
My code:
function calculate(sides) { var sides = prompt("Triangle side lengths in cm (number,number,number)"); //String will be size of 4 var nsides = sides.split(" "); //Splits content into array format //Convert Array instances to integer values a,b,c for(var loop=0;loop<=nsides.length;loop++) { if(nsides[loop]!=",") a = nsides[loop]; if(nsides[loop]!=",") b = nsides[loop]; if(nsides[loop]!=",") c= nsides[loop]; } //End for //Area Calculation var s = (a+b+c)*0.5 ; //represents the semiperimeter var area = Math.sqrt(s*(s-a)*s(s-b)*(s-c)) //area calculation //Result sides = alert("The triangle's area is " + area + " square cm"); } //End function //Main calculate(length);
I'm looking to set side a, b, and c to integers; however in order to do that I have to go through the array (I first converted it to an array from a string)
I'm going to add in some standard validation later; as of now I can't seem to place the values from the string entered into 3 separate integers being a b and c.
Other than that, is there a better way i can go about this?
Thanks.
Upvotes: 1
Views: 4249
Reputation: 71918
Maybe I misunderstand your question, but is this what you're looking for?
var sides = prompt("Triangle side lengths in cm (number,number,number)");
var nsides = sides.split(",");
var a = +nsides[0];
var b = +nsides[1];
var c = +nsides[2];
//Area Calculation
//...
Note the use of +
to force the strings from the array into numbers.
Upvotes: 1
Reputation: 12042
function calculate() {
var sides = prompt("Triangle side lengths in cm (number,number,number)"),
nsides = sides.split(","),
a = parseFloat(nsides[0]),
b = parseFloat(nsides[1]),
c = parseFloat(nsides[2]),
s = (a + b + c) / 2,
area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
alert("The triangle's area is " + area + " square cm");
return area; // return the area
}
First of all I removed your parameter, it was totally unnecessary and was overwritten by the declaration of sides
in the first line. Then I changed the split to ,
so it follows your instructions. Then you need to parse the string to integers using parseInt
and specifiying the radix 10, then you can go on with your calculations. Just a last thing, you wrote Math.sqrt(s*(s-a)*s(s-b)*(s-c))
, see that s(s-b)
causes an exception because you are using a number to be called as a function.
Upvotes: 1