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

看板C_and_CPP (C/C++)作者 (Kono Dio Da!)時間3年前 (2021/11/27 02:14), 編輯推噓1(103)
留言4則, 2人參與, 3年前最新討論串1/1
開發平台(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,再遇到下一個字元時重複 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.231.42.136 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1637950445.A.87E.html

11/27 03:22, 3年前 , 1F
缺乏輸入資料。話說你怎麼確定有空格,題目有規定嗎?
11/27 03:22, 1F

11/27 03:25, 3年前 , 2F
然後你犯了新手錯誤,sum=0那行不在else內,變成每次都
11/27 03:25, 2F

11/27 03:25, 3年前 , 3F
執行,請用大括號把else後的兩行包起來
11/27 03:25, 3F

11/27 10:13, 3年前 , 4F
題目有規定用空格分開數字 已經解決了 謝謝
11/27 10:13, 4F
文章代碼(AID): #1XeIFjX- (C_and_CPP)
文章代碼(AID): #1XeIFjX- (C_and_CPP)