下面代码有点问题:
不能计算 (-8*(2*(-2+3)*2)*10)*10
有时间会更新最新的
哎,大学没学好,现在又开始写着简单的计算器
计算一个表达式(字符串)的值
下面只是给出了计算字符串
(8*(2*(2+3)*2)*10)*10
的值
1 var temData = new Array(); 2 var temStr = new Array(); 3 (function () { 4 var cla = '(8*(2*(2+3)*2)*10)*10 '; 5 IntoStack(cla); 6 SS(); 7 })(); 8 9 function IntoStack(str) { 10 var strs = ""; 11 for (var i = 0; i < str.length; i++) { 12 switch (str[i]) { 13 case '*': 14 case '+': 15 case '-': 16 case '/': 17 case '(': 18 if (strs.length > 0) { 19 temData.push(parseFloat(strs)); 20 strs = ''; 21 } 22 if (str[i] != '(') { 23 JiSuan(str[i]); 24 } 25 temStr.push(str[i]); 26 break; 27 case ')': 28 if (strs.length > 0) { 29 temData.push(parseFloat(strs)); 30 strs = ''; 31 } 32 Kh(); 33 break; 34 default: 35 strs += str[i]; 36 break; 37 } 38 } 39 if (strs != '') { 40 temData.push(parseFloat(strs)); 41 } 42 } 43 44 function Kh() { 45 var expr = temStr.pop(); 46 var data1; 47 var data; 48 var data2; 49 while (expr != '(') { 50 data1 = temData.pop(); 51 data2 = temData.pop(); 52 data = Calculate(data2, data1, expr); 53 temData.push(data); 54 expr = temStr.pop(); 55 }; 56 var s = 's'; 57 } 58 59 60 function JiSuan(str) { 61 if (Priority(str) <= Priority(temStr[temStr.length - 1])) { 62 var data1 = temData.pop(); 63 var data2 = temData.pop(); 64 var expr = temStr.pop(); 65 var data = Calculate(data2, data1, expr); 66 temData.push(data); 67 console.log(data); 68 } 69 } 70 function SS() { 71 for (var i = temStr.length - 1; i >= 0; i--) { 72 var data1 = temData.pop(); 73 var data2 = temData.pop(); 74 var expr = temStr[i]; 75 var data = Calculate(data2, data1, expr); 76 temData.push(data); 77 console.log(data); 78 } 79 } 80 81 function Priority(expr) { ///优先级别 82 var result = 0; 83 switch (expr) { 84 case '*': 85 case '/': 86 result = 2; 87 break; 88 89 case '-': 90 case '+': 91 result = 1; 92 break; 93 94 case '(': 95 result = 0; 96 break; 97 98 case ')': 99 result = 3; 100 break; 101 default: 102 result = -1; 103 break; 104 } 105 return result; 106 } 107 function Calculate(data1, data2, expr) { 108 var result = 0; 109 switch (expr) { 110 case '*': 111 result = data1 * data2; 112 break; 113 case '/': 114 result = data1 / data2; 115 break; 116 case '-': 117 result = data1 - data2; 118 break; 119 case '+': 120 result = data1 + data2; 121 break; 122 default: return 0; 123 } 124 return result; 125 } 126