0

私は2つの数字を入力し、操作を選択してその操作を実行するjavascriptで簡単な電卓を作成しましたが、どのようにしてこのコードに正しい答えを示す唯一のものがあるのですか"+"?"-"

ここにコードがあります

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;
}

次に、最後の3行として以下の行をequal();に追加します。

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

これは単なる提案です。アプリを開発しているときに、これらすべてを行うためのさらに優れた方法が見つかると確信しています。少なくとも-ボタンが必要Cです...

于 2012-03-12T08:28:41.550 に答える