<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에서 해주시기 바랍니다.
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|
| 5727 |
잘살아보자
|
10년 전 | 477 | |
| 5726 | 10년 전 | 1050 | ||
| 5725 | 10년 전 | 1226 | ||
| 5724 | 10년 전 | 954 | ||
| 5723 |
잘살아보자
|
10년 전 | 430 | |
| 5722 |
잘살아보자
|
10년 전 | 404 | |
| 5721 |
잘살아보자
|
10년 전 | 387 | |
| 5720 |
잘살아보자
|
10년 전 | 378 | |
| 5719 |
잘살아보자
|
10년 전 | 457 | |
| 5718 |
잘살아보자
|
10년 전 | 578 | |
| 5717 |
잘살아보자
|
10년 전 | 830 | |
| 5716 |
잘살아보자
|
10년 전 | 359 | |
| 5715 |
starbros
|
10년 전 | 758 | |
| 5714 |
잘살아보자
|
10년 전 | 560 | |
| 5713 |
잘살아보자
|
10년 전 | 436 | |
| 5712 |
잘살아보자
|
10년 전 | 412 | |
| 5711 |
잘살아보자
|
10년 전 | 459 | |
| 5710 |
잘살아보자
|
10년 전 | 417 | |
| 5709 |
잘살아보자
|
10년 전 | 427 | |
| 5708 |
잘살아보자
|
10년 전 | 775 | |
| 5707 |
잘살아보자
|
10년 전 | 358 | |
| 5706 |
잘살아보자
|
10년 전 | 451 | |
| 5705 |
잘살아보자
|
10년 전 | 614 | |
| 5704 |
잘살아보자
|
10년 전 | 526 | |
| 5703 |
잘살아보자
|
10년 전 | 513 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기