相信很多人都做过计算器,也有人觉得很容易,但是我觉得真正做一个没有漏洞,一个无懈可击的计算器可真还是有点难度
的。很多人做得都不是这里有问题,便是那里有问题,很少有人可以到没什么问题的,我认为其实一个计算器的逻辑复杂度还
是满高的,至少我很难不画图就在脑子里想明白,也许是我人太笨吧,所以本人只好用本人的方法,我就事先画了个流程图来
理解。然后,再分析下,之后,才开始进行编码的。
下面是我的代码:
<script language="javascript1.1">
//定义并初始化各变量。
var first=0;
var second=0;
var result=0;
var isEditing=0;
var operation=0;
//var showValue=document.caculator.result.value;
//showValue=0;
document.caculator.result.value=0;
//各函数。
function clickNumButton(button)
{
var number=parseInt(button.value);
//alert(number);
processNumber(number)
}
function clickOperationButton(button)
{
if(operation!=0)
{
caculate();//根据运算符号和数据计算出结果。
first=result;//清空。
second=0;
isEditing=2;
document.caculator.result.value=result;//显示计算结果。
}
//退换当前运算符号。
if(button.value=='+')
operation=1;
else if(button.value=='-')
operation=2;
else if(button.value=='*')
operation=3;
else operation=4;
}
function clickEqualButton()
{
if(operation!=0)
{
caculate();//根据运算符号和数据计算出结果。
document.caculator.result.value=result;//显示计算结果。
first=0;
second=0;
result=0;
isEditing=0;
operation=0;
}
else
{
if(isEditing==1)
document.caculator.result.value=first;
else if(isEditing==2)
document.caculator.result.value=second;
else document.caculator.result.value=0;
}
}
function clickBackSpace()
{
if(isEditing==1)
{
var s=new String(""+first);
if(s.length==1)
{
s="0";
}
else s=s.substr(0,s.length-1);
//alert(s);
first=parseInt(s);
document.caculator.result.value=first;
}
else if(isEditing=2)
{
var s=new String(""+second);
if(s.length==1)
{
s="0";
}
else s=s.substr(0,s.length-1);
//alert(s);
second=parseInt(s);
document.caculator.result.value=second;
}
else{}
}
function clickClearButton()
{
first=0;
second=0;
result=0;
isEditing=0;
operation=0;
document.caculator.result.value=0;
}
function processNumber(number)
{
//修改当前编辑数标记。
if(operation==0)
{
isEditing=1;
}
else{
isEditing=2;
}
//修改当前编辑数的值。
if(number!=0)
{
if(isEditing==1)
if(first==0)
{
first=number;
document.caculator.result.value=first;
}
else
{
var s= new String((""+first)+number)
first=parseInt(s);
document.caculator.result.value=first;
}
else if(isEditing==2)
if(second==0)
{
second=number;
document.caculator.result.value=second;
}
else
{
var s= new String((""+second)+number)
second=parseInt(s);
document.caculator.result.value=second;
}
else{}
}
else
{
if(isEditing==1)
if(first!=0)
{
var s= new String((""+first)+number)
first=parseInt(s);
document.caculator.result.value=first;
//alert(document.caculator.result.value)
}
else if(isEditing==2)
if(second==0)
{
var s= new String((""+second)+number)
second=parseInt(s);
document.caculator.result.value=second;
}
else{}
}
}
function caculate()
{
if(operation==1)
{
result=first+second;
}
else if(operation==2)
result=first-second;
else if(operation==3)
result=first*second;
else if(operation==4)
result=first/second;
else {}
}
</script>