<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에서 해주시기 바랍니다.
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 5752 | 10년 전 | 496 | ||
| 5751 | 10년 전 | 541 | ||
| 5750 | 10년 전 | 341 | ||
| 5749 | 10년 전 | 408 | ||
| 5748 | 10년 전 | 815 | ||
| 5747 | 10년 전 | 596 | ||
| 5746 | 10년 전 | 302 | ||
| 5745 | 10년 전 | 348 | ||
| 5744 | 10년 전 | 349 | ||
| 5743 | 10년 전 | 284 | ||
| 5742 | 10년 전 | 287 | ||
| 5741 | 10년 전 | 642 | ||
| 5740 | 10년 전 | 320 | ||
| 5739 | 10년 전 | 310 | ||
| 5738 |
프로그램은어려워
|
10년 전 | 932 | |
| 5737 | 10년 전 | 502 | ||
| 5736 | 10년 전 | 399 | ||
| 5735 | 10년 전 | 406 | ||
| 5734 |
잘살아보자
|
10년 전 | 610 | |
| 5733 |
잘살아보자
|
10년 전 | 567 | |
| 5732 |
잘살아보자
|
10년 전 | 967 | |
| 5731 |
잘살아보자
|
10년 전 | 316 | |
| 5730 |
|
10년 전 | 1282 | |
| 5729 |
잘살아보자
|
10년 전 | 546 | |
| 5728 |
잘살아보자
|
10년 전 | 366 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기