我是C中的一个初学者,并且一直在尝试编写一个可以拉/推并显示其中元素的Stack程序。我遇到了一些我无法确定其根源的问题。 到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 100
char ch;
int contents[STACK_SIZE], top = 0;
void display();
int stack_overflow(void)
{
printf("Expression is too complex\n");
exit(EXIT_FAILURE);
}
int stack_underflow(void)
{
printf("Not enough operands in expression\n");
exit(EXIT_FAILURE);
}
void make_empty(void)
{
top = 0; //makes the element at the top of the stack = 0
}
bool is_empty(void)
{
return top == 0; //returns 1 if the top is equal to 0
}
bool is_full(void)
{
return top == STACK_SIZE; //returns 1 if the top is the maximun stack size (already full)
}
void push(char i)
{
if (is_full())
stack_overflow();
else
contents[top++] = i;
}
char pop(void)
{
if (is_empty())
stack_underflow();
else
return contents[--top];
}
int main(void)
{
int choice;
int option = 1;
int num;
printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> PUSH \n");
printf (" 2 --> POP \n");
printf (" 3 --> DISPLAY \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1: printf("Enter number you want to push: ");
scanf("%d",&num);
push(num);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
void display()
{
int i;
printf("\n\n");
for(i=0;i< top ;i++)
printf("%d\n",contents[i]);
}
STACK OPERATION
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
1
Enter number you want to push: 100
Do you want to continue(Type 0 or 1)?
1
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
1
Enter number you want to push: 500
Do you want to continue(Type 0 or 1)?
1
------------------------------------------
1 --> PUSH
2 --> POP
3 --> DISPLAY
4 --> EXIT
------------------------------------------
Enter your choice
3
100
-12
Do you want to continue(Type 0 or 1)?
0
进程返回0(0x0)执行时间:11.474秒 按任意键继续。
似乎没有正确存储元素或者可能打印错误。也许使用top变量来遍历循环是错误的?任何帮助将不胜感激。
答案 0 :(得分:2)
您的推送功能仅获得char
:
void push(char i)
char
的范围是0到255(unsigned char
)或-127到128(signed char
= char
- 这是默认设置。
你输入的'500'将因此减少(mod 256)到-12 - 这就是你打印的内容。
您需要将参数设为int
,它应该有效。