I have been messing around with HTML and manipulating SVG’s. As practice I have created a page that uses javascript to solve the pythagorean theorem and display the triangle in a 300h x 300w area. My problem I think is that when there is too much of a difference between variable “a” and variable “b” the comparison “if(a>b)” isn’t working properly. So it works perfectly for a=55 and b=32 or even a=5555 and b=5000 but if I do a=1001 and b=55 it seems to run it as if b is greater than a.
<h2>Pythagorean theorem</h2>
<p>Enter Variable "a"<input id="vara" type="text"></p>
<p>Enter Variable "b"<input id="varb" type="text"></p>
<p><span id="a">a</span><sup>2</sup> +
<span id="b">b</span><sup>2</sup> =
<span id="c">c</span><sup>2</sup></p>
<script>
function pythagorean(){
var a=document.getElementById("vara").value;
var b=document.getElementById("varb").value;
var x=a * a + b * b;
var c=Math.sqrt(x);
if(a>b){
ay=0
bx=b/a*300
}
else{
ay=300-(a/b*300)
bx=300
}
document.getElementById("a").innerHTML=a;
document.getElementById("b").innerHTML=b;
document.getElementById("c").innerHTML=c;
document.getElementById('trianglepoints').setAttribute("points",bx+",300 0,300 0,"+ay);
}
</script>
<svg id="triangle xmlns="http://www.w3.org/2000/svg" version="1.1" height="300" width="300">
<polygon id="trianglepoints" points=""
style="fill:red;stroke:black;stroke-width:1;">
</svg>
<br />
<button type="button" onclick="pythagorean()">calculate</button>
Be sure that you cast the String values returned by
element.valueto Number:Otherwise, when you compare
a > bit will do a string comparison, and'1001'is less than'55'(first characters compared first).