0

I created a simple calculator in javascript where I will input 2 numbers then select an operation and perform that operation but how come in this code the only thing that shows a correct answer is "+" and "-"

here's the code

var fnum;
var secondNum;
var operation;

function msg(val) {

fnum = document.getElementById("fnumtext").value += val;

}
function showOperation(oper) 
{
    document.getElementById("fnumtext").value = "";
    document.getElementById("operation").value = oper;
    operation = oper;
}

function equal() {
    secondNum = document.getElementById("fnumtext").value;
    var num1 = parseInt(fnum) 
    var num2 = parseInt(secondNum);
    if(document.getElementById("operation").value == "+"){
    document.getElementById("fnumtext").value = parseInt(fnum) + parseInt(secondNum);
    }else if(document.getElementById("operation").value == "-"){
        document.getElementById("fnumtext").value = num1-num2;
    }else if(document.getElementById("operation").value == "*"){
        document.getElementById("fnumtext").value = num1 * num2;
    }else if(document.getElementById("operation").value == "/"){
        document.getElementById("fnumtext").value = (parseInt(fnum) / parseInt(secondNum));
    }
}
4

1 回答 1

0

像这样重写你的msg()

function msg(val) {
if(!secondNum && fnum)
    secondNum = document.getElementById("fnumtext").value += val;
if(!fnum)
    fnum = document.getElementById("fnumtext").value += val;
}

然后将下面的行作为最后三行添加到equal();

function equal() {
    ...
    fnum=false;
    secondNum=false;
    return;
}

这只是一个建议,我相信您在开发应用程序时会找到更好的方法来完成这一切。至少它需要一个C按钮...

于 2012-03-12T08:28:41.550 回答