Let me start by saying this is for my second project in my Javascript class. I am not asking anyone do it for me. Frankly I'd rather figure it out myself. Although I am in the need of a little direction. There are several parts of this project but this part seems to getting the best of me. What I am trying to do is determine whether a triangle is isosceles, scalene, or equilateral. And then print out the result. I have both scalene and equilateral working correctly. And I believe isosceles as well. The problem occurs when printing out the result. Since an isosceles has two sides that are equal when I enter in 3 of the same number, my program prints out the statement for both isosceles and equilateral. Here are the two functions i have for checking the triangle. function isIsosceles(s1,s2,s3) { if (s1 == s2 || s2 == s3 || s1 == s3) { return true; } } function isEquilateral(s1,s2,s3) { if (s1 == s2 && s2 == s3) { return true; } } Code (markup): Here is my code for printing the results: if (isIsosceles(s1,s2,s3) == true) { document.write("<br>The triangle is isosceles"); } if (isEquilateral(s1,s2,s3) == true) { document.write("<br>The triangle is equilateral"); } Code (markup): When the user inputs 5, 5, 5. Both statements print. Can anyone provide a little guidance?
The problem is that an equilateral triangle DOES had two sides the same, so by your test it is also an isosceles. Basically you should check to see if it is an equilateral first. The best place to do that would probably be in the isIsosceles function, because you could always be sure you got the correct answer then: function isIsosceles(s1,s2,s3) { if(isEquilateral(s1,s2,s3)) return false; if (s1 == s2 || s2 == s3 || s1 == s3) { return true; } } Code (markup):
lephron, Thank you for the reply. I was thinking of something similar but I kept adding it to the conditional statement of the isIsosceles function. This makes more sense to me. I am glad I was at least thinking in the right area. I just have one other question about this. if(isEquilateral(s1,s2,s3)) return false; Code (markup): I tested it out as followed and it worked. if (isEquilateral(s1,s2,s3) == true) { return false } Code (markup): Am I correct in assuming that when you call a function that will return either true or false you do not have to check the result of that return with a comparison operator?
Yes that is correct. An if statement (or any other conditional such as while, for etc) evaluates it's arguments to either true or false. So if you have something like: if(myVal == 10) Code (markup): then javascript would evaluate the part in brackets to either true or false. Therefore "== true" is redundant, because if it evaluates to true then it will always == true. Again, instead of == false you can just use if(!isSomething()) Code (markup): But beware that javascript also evaluates 0 and '' to false in that situation.