我已经制作了一段时间的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;
}
答案 0 :(得分:0)
我刚测试过它,你的代码运行正常。我的假设是你试图使用平方根功能而不是在num2
中放置任何东西,这对于计算数字的平方根来说似乎很自然。但是,如果您打开错误控制台,当您尝试在操作员之后没有任何内容进行评估时,您会注意到eval
不喜欢它。我的建议是将eval
移到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;
}