[英]Adding Decimal to calculator
我使用javascript制作了一個計算器,它可以正常工作,但存在一些問題。
這是javascript代碼:
<script type="text/javascript">
var valid=false ,operand='', numCounter=1, firstNum=null, secondNum=null;
function remov(){
document.getElementById('result').value = null;
secondNum = firstNum = null;
numCounter=1;
}
function show(id){
var val = document.getElementById(id).value;
if(id=='+' || id=='-' || id=='*' || id=='/' || id=='^' || id=='√')
{
valid=true;
if(numCounter > 1){
calc();
}
firstNum=Number(document.getElementById('result').value);
numCounter++;
operand=id;
}
else if(id == 'equal')
{
calc();
numCounter=1;
}
else
{
if(valid){
document.getElementById('result').value = null;
valid=false;
}
document.getElementById('result').value += val;
}
}
function calc(){
if(numCounter > 1){
secondNum=Number(document.getElementById('result').value);
}else{
firstNum=Number(document.getElementById('result').value);
}
switch(operand)
{
case '+':
document.getElementById('result').value = firstNum+secondNum;
break;
case '-':
document.getElementById('result').value = firstNum-secondNum;
break;
case '/':
if(firstNum != 0)
document.getElementById('result').value = firstNum/secondNum;
else
document.getElementById('result').value = "Error";
break;
case '*':
document.getElementById('result').value = firstNum*secondNum;
break;
case '^':
document.getElementById('result').value = Math.pow(firstNum,secondNum);
break;
case '√':
document.getElementById('result').value = Math.sqrt(firstNum);
break;
}
}
</script>
這是HTML
<body oncontextmenu="return false">
<div id="cal">
<input id="result" type="text" readonly /><br/>
<button value="1" id="1" onclick="show(1)">1</button>
<button value="2" id="2" onclick="show(2)">2</button>
<button value="3" id="3" onclick="show(3)">3</button>
<button value="+" id="+" onclick="show('+')">+</button><br/>
<button value="4" id="4" onclick="show(4)">4</button>
<button value="5" id="5" onclick="show(5)">5</button>
<button value="6" id="6" onclick="show(6)">6</button>
<button value="-" id="-" onclick="show('-')">-</button><br/>
<button value="7" id="7" onclick="show(7)">7</button>
<button value="8" id="8" onclick="show(8)">8</button>
<button value="9" id="9" onclick="show(9)">9</button>
<button value="*" id="*" onclick="show('*')">*</button><br/>
<button value="." id="." onclick="show('.')">.</button>
<button value="0" id="0" onclick="show(0)">0</button>
<button value="√" id="√" onclick="show('√')">√</button>
<button value="/" id="/" onclick="show('/')">/</button><br/>
<button onclick="remov()">C</button>
<button value="^" id="^" onclick="show('^')">^</button>
<button id="equal" value="=" onclick="show('equal')">=</button>
</div>
</body>
對於小數,您可以使用toFixed
- http://www.w3schools.com/jsref/jsref_tofixed.asp
至於其他問題,不知道。 當您單擊一次時,對其他按鈕有用嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.