對於我的編程類,我必須編寫一個計算器,它可以與堆棧一起工作。堆棧計算器改變變量的值
這是我堆棧本身使得代碼:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
double stk[MAXSIZE]; //Stack array
int top=-1; //Top position in stack
void push(double n);
double pop(void);
void display(void);
/* Add an element to the stack */
void push(double n) {
if (top == (MAXSIZE - 1)) {
printf ("Stack is full\n");
}
else {
//s.top++;
//stk = (double *) malloc(MAXSIZE*sizeof(double));
stk[++top] = n;
}
return;
}
/* Remove and return the top element from the stack */
double pop() {
double num;
if (top == -1) {
printf ("Stack is empty\n");
return (top);
}
else {
num = stk[top--];
printf ("Pop:%f\n", num); //Debugging line
return (num);
}
}
/* Prints all elements in the stack */
void display() {
int i;
if (top == -1) {
printf ("Stack is empty\n");
return;
}
else {
for (i = top; i >= 0; i--) {
printf ("%f\n", stk[i]);
}
}
}
這是計算器(這是在不同的文件,我用makefile編譯):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int isNumber(const char *s);
void insert(double num);
void sum(void);
int main(int argc, char *argv[]) {
int loop = 1;
char input[10];
/* Main Loop */
while (loop == 1) {
printf("> ");
scanf(" %[^\n]", input);
if (isNumber(input)) {
double nu = atof(input);
insert(nu);
}
else if (strcmp(input, "+") == 0)
sum();
else if (strcmp(input, "l") == 0)
list();
else if (strcmp(input, "exit") == 0) //exit
loop = 0;
} //end while
} //end main
int isNumber(const char *s) {
while (*s) {
if((*s<'0' || *s>'9') && *s!='-' && *s!='.')
return 0;
s++;
}
return 1;
}
void insert(double num) {
push(num);
}
/* This function is called when the user enters a '+' instead of a number into the command line. It takes the top two numbers from the stack and adds them together */
void sum() {
double num1, num2, res;
num1 = pop();
num2 = pop();
res = num1+num2;
printf("num1:%f num2:%f sum:%f\n", num1, num2, res); //Debug
}
int list() {
display();
}
程序編譯得很好。當我運行它,我通過輸入5接着是6後跟一個+測試它,我得到這樣的輸出:
Pop:6.000000
Pop:4.000000
num1:13.000000 num2:13.000000 sum:26.000000
因此很明顯的是,POP()函數返回的數字是正確的,但將其分配給當由於某些原因,計算器功能中的變量將其變爲13。它並不總是13,對於更大的數字它更高;進入500退貨14,退貨1000退貨15,退貨退貨16,等等。
我最初使用int數組創建了我的堆棧,並且它實際上完美工作(如果將所有雙精度值更改爲整數,它仍然會執行)。由於display()函數可以正確打印用戶輸入的所有值,堆棧本身似乎也能正常工作。
我真的很困惑,因爲錯誤來自哪裏,我實際上正在考慮將整個堆棧重寫爲鏈表,而我想給這個最後一個鏡頭。
在此先感謝您的幫助。編輯:我在我的計算器文件中添加了一個#include「Stack.h」(更改Stack.c到Stack.h),並處理了makefile,現在它可以工作。我不知道最初發生了什麼,但我很高興它的工作原理。
我不認爲你已經呈現在我們面前爲你描述都不可能表現的代碼。你確定你已經清除了任何徘徊的對象文件,並且正在編譯你在這裏顯示的內容嗎? –
不,我忽略了一些我認爲不相關的部分。我意識到這可能是一個錯誤,我會用整個文件編輯。 – Zhior