毕达哥拉斯在javascript中的公式

时间:2015-09-14 11:36:40

标签: javascript

我是编程的初学者。我尝试用javascript制作毕达哥拉斯的公式。我无法用英语解释得很好,所以你能亲自试一下,看看我的代码有什么问题以及如何修复它?

以下是代码:

var a = document.getElementById("a").innerHTML;
var b = document.getElementById("b").innerHTML;
var c = document.getElementById("c").innerHTML;

function fungsi(x) {
  c = sqrt(a * a + b * b)
};

function fungsi(y) {
  a = sqrt(c * c - b * b)
};

function fungsi(z) {
  b = sqrt(c * c - a * a)
};
if (c = null) {
  getElementById("tombol").onclick = fungsi(x);
} else if (a = null) {
  getElementById("tombol").onclick = fungsi(y);
} else {
  getElementById("tombol").onclick = fungsi(z);
}
<input id="a" type=number>
<br>
<input id="b" type=number>
<br>
<input id="c" type=number>
<br>
<button id="tombol" onclick=fungsi()>hitung</button>

2 个答案:

答案 0 :(得分:1)

因为你的行为(而且很多人甚至都不打扰):

您的HTML:

<input id="a" type=number>
<br>
<input id="b" type=number>
<br>
<input id="c" type=number>
<br>
<button id="tombol" onclick="fungsi()">hitung</button>

您的Javascript:

function fungsi()
{
    var vals = {};

    if( document.getElementById("a").value.length > 0 )
    {
        vals.a = document.getElementById("a").value;
    }
    if( document.getElementById("b").value.length > 0 )
    {
        vals.b = document.getElementById("b").value;
    }
    if( document.getElementById("c").value.length > 0 )
    {
        vals.c = document.getElementById("c").value;
    }

    if( Object.keys(vals).length < 2 )
    {
        alert('Need 2 values');
        return;
    }

    if( typeof vals.a != 'undefined' && typeof vals.b != 'undefined' )
    {
        alert( ( Math.sqrt( vals.a * vals.a + vals.b * vals.b ) ) );
    }
    else if( typeof vals.b != 'undefined' && typeof vals.c != 'undefined' )
    {
        alert( ( Math.sqrt( vals.b * vals.b + vals.c * vals.c ) ) );
    }
    else if( typeof vals.a != 'undefined' && typeof vals.c != 'undefined' )
    {
        alert( ( Math.sqrt( vals.a * vals.a + vals.c * vals.c ) ) );
    }
}

应该足以让你推动;)

答案 1 :(得分:0)

对于Pythagore函数,我只是在有帮助的情况下写了这个。

function pythagore(a, b, hypoth) {
    let result;
    let ab = [a, b];
    if(hypoth === null) {
        return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
    } else if (a === null || b === null) {
        ab = ab[0] || ab[1];
        return Math.sqrt(Math.pow(hypoth, 2) - Math.pow(ab, 2));
    }
}
console.log(pythagore(5, null, 13))
// Expected output : 12