1

我一直在制作一个 javascript 计算器,我可以获得所有基本函数和 pow() 函数,但我无法让它执行 Math.sqrt() 函数。在过去的几天里,我遇到了这个问题。这是我的代码,在此先感谢:

function calc()
{
    var D = "";
    var A = document.getElementById("num1").value;
    var B = document.getElementById("op").value;
    var C = document.getElementById("num2").value;
    X = parseInt(A);
    S = 2
    var Z = "If you're seeing this, that means that the code isn't working!!"
    D = eval(A + B + C);
    if (B == "%")
    {
        D = ""
        Z = Math.sqrt(X)*1
    }
    else if (B == "^")
    {
        D = ""
        Z = Math.pow(X, C)
    }
    else if (B == "^2")
    {
        D = ""
        Z = Math.pow(X, S)
    }
    else if (B == "")
    {
        D = "No Operator"
        Z = ""
    }
    document.getElementById("result").value = D;
    document.getElementById("sqrt-result").value = Z;       
    return false;
}
4

1 回答 1

0

我刚刚对其进行了测试,您的代码运行良好。我的假设是您正在尝试使用平方根功能而不是放入任何东西num2,这对于计算数字的平方根来说似乎很自然。eval然而,如果你打开你的错误控制台,你会注意到当你试图在一个运算符之后评估一些没有任何东西的东西时,你会注意到它不喜欢它。我的建议是将seval下面移动,if以便仅在需要时使用它。

function calc()
{
    var D = "";
    var A = document.getElementById("num1").value;
    var B = document.getElementById("op").value;
    var C = document.getElementById("num2").value;
    X = parseInt(A);
    S = 2
    var Z = "If you're seeing this, that means that the code isn't working!!"
    if (B == "%")
    {
        Z = Math.sqrt(X)*1
    }
    else if (B == "^")
    {
        Z = Math.pow(X, C)
    }
    else if (B == "^2")
    {
        Z = Math.pow(X, S)
    }
    else if (B == "")
    {
        D = "No Operator"
        Z = ""
    } else {
        // Only do this if not doing any of the above calculations
        D = eval(A + B + C);
    }
    document.getElementById("result").value = D;
    document.getElementById("sqrt-result").value = Z;       
    return false;
}
于 2013-05-16T14:49:02.047 回答