计算一个字符串,字符串包含数字和加减符号,返回整数。请用C语言实现
时间: 2023-12-10 19:40:41 浏览: 35
以下是一个简单的 C 语言实现,使用栈来处理加减运算:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void stack_init(Stack *s) {
s->top = -1;
}
void stack_push(Stack *s, int value) {
if (s->top == STACK_SIZE - 1) {
fprintf(stderr, "Stack overflow\n");
exit(EXIT_FAILURE);
}
s->data[++(s->top)] = value;
}
int stack_pop(Stack *s) {
if (s->top == -1) {
fprintf(stderr, "Stack underflow\n");
exit(EXIT_FAILURE);
}
return s->data[(s->top)--];
}
int calculate(char *s) {
Stack nums, ops;
stack_init(&nums);
stack_init(&ops);
int num = 0;
while (*s != '\0') {
if (isdigit(*s)) {
num = num * 10 + (*s - '0');
} else if (*s == '+' || *s == '-') {
stack_push(&nums, num);
num = 0;
while (ops.top != -1 && (ops.data[ops.top] == '+' || ops.data[ops.top] == '-')) {
int b = stack_pop(&nums);
int a = stack_pop(&nums);
char op = stack_pop(&ops);
int result = (op == '+') ? a + b : a - b;
stack_push(&nums, result);
}
stack_push(&ops, *s);
}
s++;
}
stack_push(&nums, num);
while (ops.top != -1) {
int b = stack_pop(&nums);
int a = stack_pop(&nums);
char op = stack_pop(&ops);
int result = (op == '+') ? a + b : a - b;
stack_push(&nums, result);
}
return stack_pop(&nums);
}
int main() {
char s[] = "3+2-1+5";
int result = calculate(s);
printf("Result: %d\n", result);
return 0;
}
```
该程序首先定义了一个栈结构体,包含一个整数数组和一个指向栈顶的指针 top。stack_init() 函数初始化一个新栈,stack_push() 和 stack_pop() 分别用于压入和弹出栈顶元素。calculate() 函数使用两个栈 nums 和 ops,分别存储数字和操作符。在遍历字符串时,如果遇到数字,则将其加入 num 变量中。如果遇到加减符号,则将当前数字压入 nums 栈,并处理 ops 栈中已有的加减运算。最后,将 nums 栈中剩余的数字进行加减运算,返回最终结果。