[問題] C語言 堆疊 後序 輸入運算元10以上
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
DEVC++
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
用堆疊寫後式運算式
但輸入的運算元要求要可以10以上的
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版)
/* 程式範例: Ch5-3-2.c */
#include <stdio.h>
#include <stdlib.h>
#include "stack.c"
/* 是否是運算子 */
int isOperator(char op) {
switch ( op ) {
case '+':
case '-':
case '*':
case '/': return 1; /* 是運算子 */
default: return 0; /* 不是運算子 */
}
}
/* 計算二元運算式的結果 */
int cal(int op,int operand1,int operand2) {
switch ( (char) op ) {
case '*': return ( operand2 * operand1 ); /* 乘 */
case '/': return ( operand2 / operand1 ); /* 除 */
case '+': return ( operand2 + operand1 ); /* 加 */
case '-': return ( operand2 - operand1 ); /* 減 */
}
}
/* 後序運算式的計算 */
int postfixEval(char *exp) {
int operand1 = 0; /* 第1個運算元變數 */
int operand2 = 0; /* 第2個運算元變數 */
int pos = 0; /* 運算式字串索引 */
/* 剖析運算式字串迴圈 */
while ( exp[pos] != '\0' && exp[pos] != '\n') {
if ( isOperator(exp[pos]) ) { /* 是不是運算子 */
/* 從堆疊取出兩個運算元 */
operand1 = pop();
operand2 = pop();
/* 計算結果存回堆疊 */
push(cal(exp[pos],operand2,operand1));
}
else /* 這是運算元, 存入運算元堆疊 */
push(exp[pos]-48);
pos++; /* 下一個字元 */
}
return pop(); /* 傳回後序運算式的結果 */
}
/* 主程式 */
int main() {
char exp[1000]; /* 運算式的字串變數 */
printf("請輸入後序運算式 ==> ");
gets(exp); /* 讀取運算式 */
printf("運算式: %s = %d\n", exp, postfixEval(exp));
system("PAUSE");
return 0;
}
補充說明(Supplement):
我是有想法想說用空格格開
例如:10 12 + 6 *
得到結果132這樣
然後以空格做為判斷式存入堆疊
但不知道該在哪裡加入判斷式
有請板上資結神人幫忙謝謝~~
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.172.90.238
→
11/04 20:55, , 1F
11/04 20:55, 1F
→
11/04 20:56, , 2F
11/04 20:56, 2F
→
11/04 21:11, , 3F
11/04 21:11, 3F
→
11/04 22:13, , 4F
11/04 22:13, 4F
→
11/04 22:14, , 5F
11/04 22:14, 5F
→
11/04 22:15, , 6F
11/04 22:15, 6F
→
11/04 22:19, , 7F
11/04 22:19, 7F
→
11/04 22:19, , 8F
11/04 22:19, 8F
→
11/04 22:20, , 9F
11/04 22:20, 9F
→
11/04 22:21, , 10F
11/04 22:21, 10F
→
11/04 22:22, , 11F
11/04 22:22, 11F
→
11/04 22:22, , 12F
11/04 22:22, 12F
→
11/04 22:23, , 13F
11/04 22:23, 13F
→
11/04 22:24, , 14F
11/04 22:24, 14F
→
11/04 22:24, , 15F
11/04 22:24, 15F
→
11/04 22:24, , 16F
11/04 22:24, 16F
→
11/04 22:26, , 17F
11/04 22:26, 17F
→
11/04 22:29, , 18F
11/04 22:29, 18F
→
11/04 22:30, , 19F
11/04 22:30, 19F
→
11/04 22:32, , 20F
11/04 22:32, 20F
→
11/04 22:38, , 21F
11/04 22:38, 21F
→
11/04 22:39, , 22F
11/04 22:39, 22F
→
11/04 22:58, , 23F
11/04 22:58, 23F