做一個計算器的練習題,用if...else做可以么?
<script type="text/javascript">
?? function count(){
??? var a = document.getElementById("txt1").value;
??? var b = document.getElementById("txt2").value;
??? var c = document.getElementById("select").value;
??? if(c==+){
??????? d=parseInt(a)+parseInt(b);
??? }
??? else if(c==-){
??????? d=parseInt(a)-parseInt(b);
??? }
??? else if(c==*){
??????? d=parseInt(a)*parseInt(b);
??? }
??? else{
??????? d=parseInt(a)/parseInt(b);
??? }
??? document.getElementById("fruit").value=d;
?? }
? </script>
?</head>
?<body>
?? <input type='text' id='txt1' />
?? <select id='select'>
?? ??? ?<option value='+'>+</option>
?? ??? ?<option value="-">-</option>
?? ??? ?<option value="*">*</option>
?? ??? ?<option value="/">/</option>
?? </select><br/>
?? <input type='text' id='txt2' />
?? <input type='button' value=' = ' onclick="count()" /><br/> <!--通過 = 按鈕來調用創(chuàng)建的函數,得到結果-->
?? <input type='text' id='fruit' />? ?
?</body>
我用這個方法做,第一遍是可以正常運行的,但是刷新后就無法運行了,請問是為啥?我覺得if...else在這個邏輯上是通的?。?br />
2016-04-18
這個練習題可以用if……else if……結構來做,用switch來判斷加減乘除等運算符還更簡單些。
2016-04-22
除數為零你們考慮了嗎?