<script>
function getOpPrec(op) {
switch(op) {
case '*': case '/':
return 5;
case '+': case '-':
return 3;
case '(':
return 1;
}
}
function whoPrecOp(op1, op2) {
var op1Prec = getOpPrec(op1), op2Prec = getOpPrec(op2);
if (op1Prec > op2Prec)
return 1;
else if (op1Prec < op2Prec)
return -1;
else
return 0;
}
function postfix(exp) {
var dst = [], src = [], op = [],
src = exp.replace(' ','').match(/[\d\.]+|[+\-*()/]/g);
while (src.length) {
var tok = src.shift();
if (!isNaN(tok)) {
dst.push(tok);
} else {
switch(tok) {
case '(':
op.push(tok);
break;
case ')':
while(1) {
var popOp = op.pop();
if (popOp == '(')
break;
dst.push(popOp);
}
break;
case '+': case '-':
case '*': case '/':
while (op.length && whoPrecOp(op[op.length-1], tok) > 0)
dst.push(op.pop());
op.push(tok);
break;
}
}
}
while (op.length)
dst.push(op.pop());
return dst;
}
function evalExp(exp) {
var dst = [], op1, op2;
while (exp.length) {
var tok = exp.shift();
if (!isNaN(tok))
dst.push(tok);
else {
op2 = Number(dst.pop());
op1 = Number(dst.pop());
switch (tok) {
case '+':
dst.push(op1 + op2);
break;
case '-':
dst.push(op1 - op2);
break;
case '*':
dst.push(op1 * op2);
break;
case '/':
dst.push(op1 / op2);
break;
}
}
}
return dst;
}
function cal(src) {
document.getElementById('result').value = evalExp(postfix(src));
}
</script>
입력 <input type="text" id="input" name="src" value="" onblur="cal(this.value)" /> =
결과 <input id="result" type="text" name="result" size="10" value="" />
게시판 목록
팁게시판
질문은 상단의 QA에서 해주시기 바랍니다.
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 5602 |
잘살아보자
|
11년 전 | 3070 | |
| 5601 |
잘살아보자
|
11년 전 | 2404 | |
| 5600 |
잘살아보자
|
11년 전 | 5744 | |
| 5599 |
잘살아보자
|
11년 전 | 3385 | |
| 5598 |
잘살아보자
|
11년 전 | 1832 | |
| 5597 |
잘살아보자
|
11년 전 | 2083 | |
| 5596 |
잘살아보자
|
11년 전 | 1341 | |
| 5595 |
잘살아보자
|
11년 전 | 1308 | |
| 5594 |
잘살아보자
|
11년 전 | 1455 | |
| 5593 | 11년 전 | 2507 | ||
| 5592 |
잘살아보자
|
11년 전 | 2326 | |
| 5591 |
잘살아보자
|
11년 전 | 2335 | |
| 5590 |
잘살아보자
|
11년 전 | 2421 | |
| 5589 |
잘살아보자
|
11년 전 | 1409 | |
| 5588 |
잘살아보자
|
11년 전 | 1888 | |
| 5587 |
잘살아보자
|
11년 전 | 1226 | |
| 5586 |
잘살아보자
|
11년 전 | 1034 | |
| 5585 | 11년 전 | 3563 | ||
| 5584 | 11년 전 | 1175 | ||
| 5583 | 11년 전 | 2417 | ||
| 5582 | 11년 전 | 1465 | ||
| 5581 | 11년 전 | 2880 | ||
| 5580 | 11년 전 | 1731 | ||
| 5579 | 11년 전 | 1704 | ||
| 5578 | 11년 전 | 1268 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기