对于我的编程类,我必须编写一个计算器,它可以与堆栈一起工作。堆栈计算器改变变量的值
这是我堆栈本身使得代码:
#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