[問題] 後輸入運算式,堆疊後歸零

作者: justgetup (gonna fight)   2021-11-27 02:14:03
開發平台(Platform): (Ex: Win10, Linux, ...)
DEVC++
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
在PUSH(sum)完資料後 用sum=0清空,但之後sum輸入的資料都變成0
餵入的資料(Input):
預期的正確結果(Expected Output):
可以正常的四則運算
錯誤結果(Wrong Output):
結果都為0
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
int postfixEval(char *exp) {
int operand1 = 0; /* 第1個運算元變數 */
int operand2 = 0; /* 第2個運算元變數 */
int sum = 0; /* 判斷式所需之變數 */
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
if (exp[pos] >= '0' && exp[pos] <= '9')
*/
sum = sum*10+(exp[pos]-'0');
else
push(sum);
sum = 0;
pos++; /* 下一個字元 */
}
return pop(); /* 傳回後序運算式的結果 */
}
補充說明(Supplement):
想法是一個字元讀完,如果下一個也是字元就sum=A*10+B,遇到空格
push(sum),然後sum歸0,再遇到下一個字元時重複
作者: Schottky (順風相送)   2021-11-27 03:22:00
缺乏輸入資料。話說你怎麼確定有空格,題目有規定嗎?然後你犯了新手錯誤,sum=0那行不在else內,變成每次都執行,請用大括號把else後的兩行包起來
作者: justgetup (gonna fight)   2021-11-27 10:13:00
題目有規定用空格分開數字 已經解決了 謝謝

Links booklink

Contact Us: admin [ a t ] ucptt.com