给a、b、c、d添加+,-,*,/得到期望的value,结果是逆波兰式
代码
<html>
<head>
<title></title>
<style></style>
<script language="javascript">
var want_value =0;
var op = new Array
(
new Array('+',function (x,y){return x+y;}),
new Array('-',function (x,y){return x-y;}),
new Array('*',function (x,y){return x*y;}),
new Array('/',function (x,y){ if (y==0){return "error";} else return x/y;})
);
var pro_num = function (i){
return '('+i+')';
}
var get_remove_by_index = function (list,index){
var r=[];
for(var i=0;i<list.length;++i){
if(i!=index)
r.push(list[i]);
}
return r;
}
var con = function (list,v,rv){
var length=list.length;
if(length==0){
if(rv-want_value ==0){
//console.log(v+'='+rv);
document.getElementById('result').value+=v+'='+rv+'\n';
}
return;
}
for(var i=0;i<length;++i){
for(var j=0; j< op.length;++j){
var v1=pro_num(list[i])+v+op[j][0];
var rv1=op[j][1](list[i],rv);
if(rv1!='error') con(get_remove_by_index(list,i),v1,rv1);
}
}
}
var con_real = function(a,b,c,d,v){
var list=[a,b,c,d];
want_value =v;
var length = list.length;
if(length >1){
for(var i=0;i<length;++i){
con(get_remove_by_index(list,i),pro_num(list[i]),list[i]);
}
}
}
var on_button_click = function(){
var a=parseFloat(document.getElementById('a').value);
var b=parseFloat(document.getElementById('b').value);
var c=parseFloat(document.getElementById('c').value);
var d=parseFloat(document.getElementById('d').value);
var v=parseFloat(document.getElementById('value').value);
document.getElementById('result').value=""
con_real(a,b,c,d,v);
}
</script>
</head>
<body>
<form>
<div>
value:<input type="text" id="value" value="24"/>
a:<input type="text" id="a"/>
b:<input type="text" id="b"/>
c:<input type="text" id="c"/>
d:<input type="text" id="d"/>
</div>
<div>
<input type="button" value="Cal" onClick="on_button_click()"/>
</div>
<textarea style="width:100%;height:800px" id='result'></textarea>
</form>
</body>
</html>
posted on 2009-11-02 16:09
zarra 阅读(162)
评论(0) 编辑 收藏