写一个C语言 用栈实现算术运算
时间: 2024-05-27 10:13:42 浏览: 94
当然,我可以为您写出一个简单的C程序,用栈来实现基本的算术运算。下面是例子代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
int stack[MAX_STACK_SIZE];
int top = -1;
int pop()
{
if(top == -1)
printf("\nERROR: Stack is Empty!!!\n");
else
return(stack[top--]);
}
void push(int item)
{
if(top == (MAX_STACK_SIZE-1))
printf("\nERROR: Stack is Full!!!\n");
else
stack[++top] = item;
}
int main()
{
char expression[100];
char *p;
int num;
printf("Enter the expression: ");
scanf("%s", expression);
p = expression;
while(*p != '\0')
{
if(isdigit(*p))
{
num = *p - '0';
push(num);
}
else
{
switch(*p)
{
case '+':
push(pop() + pop());
break;
case '-':
push(pop() - pop());
break;
case '*':
push(pop() * pop());
break;
case '/':
push(pop() / pop());
break;
default:
printf("\nERROR: Invalid Expression!!!\n");
return 1;
}
}
p++;
}
printf("\nThe result of expression %s is %d\n", expression, pop());
return 0;
}
希望这个例子可以帮助您!
阅读全文
相关推荐


















