原代碼問題
- `stackempty`、`stackfull` 未實現直接返回。
- `popstack` 中 `x=data.[S.top]` 語法錯誤。
- 轉八進制卻用 `n%2`、`n/2`(二進制邏輯)。
- 主函數 `void main()` 非標準。
- 輸出循環重複 `S.top--` 導致棧指針錯亂。
修正完整代碼
#include <stdio.h>
#include <stdbool.h>
typedef struct {
int data[100];
int top;
} SeqStack;
void init(SeqStack *s) { s->top = -1; }
bool empty(SeqStack *s) { return s->top == -1; }
bool full(SeqStack *s) { return s->top == 99; }
bool push(SeqStack *s, int x) {
if (full(s)) return false;
s->data[++s->top] = x;
return true;
}
bool pop(SeqStack *s, int *x) {
if (empty(s)) return false;
*x = s->data[s->top--];
return true;
}
int main() {
SeqStack s; init(&s);
int n, x;
printf("請輸入非負十進制整數:");
scanf("%d", &n);
if (n == 0) { printf("對應八進制:0\n"); return 0; }
while (n != 0) {
push(&s, n % 8); // 關鍵:模 8
n /= 8;
}
printf("對應八進制:");
while (!empty(&s)) {
pop(&s, &x);
printf("%d", x);
}
printf("\n");
return 0;
}
關鍵修正點
- 棧操作封裝指針參數,邏輯完整。
- 八進制核心:`n % 8` 入棧,`n /= 8` 疊代。
- 輸出循環僅 `pop` 自動遞減 `top`,不再手動 `--`。
- 增加 `n==0` 特判,避免空棧無輸出。