输入一个算式(没有空格),遇等号“=”表示输入结束,输出结果。假设计算器只能进行加、减、乘、除运算,运算数和结果都是整数,4种运算符的优先级相同,按“从左到右”的顺序计算。用c写
时间: 2024-12-02 19:21:05 浏览: 17
java编写一个类,该类可以进行加、减、乘、除四则运算,并且输出运算结果
你可以使用C语言编写一个简单的计算器函数来处理这样的算术表达式。这里是一个基本的示例,我们使用栈来存储操作数和运算符:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct {
int num;
char op;
} Token;
int is_number(char c) {
return (isdigit(c) || c == '-');
}
void push(int num, Stack *s) {
s->top++;
s->items[s->top] = (Token){num, 'E'};
}
void pop(Stack *s, int *num, char *op) {
if (s->top > 0) {
*num = s->items[s->top - 1].num;
*op = s->items[s->top - 1].op;
s->top--;
}
}
double calculate(Stack *s) {
double result = 0, prev_num = 0;
char op = ' ';
while (s->top > 0) {
Token token = s->items[s->top];
if (is_number(token.op)) {
if (op != 'E') {
result += prev_num * pow(10, token.num);
prev_num = 0;
}
prev_num *= 10;
prev_num += token.num;
} else {
prev_num *= pow(10, token.num);
switch (op) {
case '+':
result += prev_num;
break;
case '-':
result -= prev_num;
break;
case '*':
result *= prev_num;
break;
case '/':
if (prev_num != 0)
result /= prev_num;
else
printf("Error: Division by zero.\n");
break;
}
prev_num = 0;
op = token.op;
}
pop(s, &prev_num, &op);
}
if (op != 'E')
result += prev_num;
return result;
}
int main() {
Stack s;
s.top = -1;
char input[100];
fgets(input, sizeof(input), stdin);
for (size_t i = 0; i < strlen(input); i++) {
if (input[i] == ' ') continue;
if (isdigit(input[i])) {
int num = input[i] - '0';
while (i + 1 < strlen(input) && is_number(input[i + 1])) {
num = num * 10 + (input[i + 1] - '0');
i++;
}
push(num, &s);
} else {
pop(&s, NULL, &input[i]);
if (s.top == -1) {
printf("Error: Unexpected operator.\n");
break;
}
char op = input[i];
if (op == '=') {
break;
}
pop(&s, NULL, &op);
if (op == '/') {
if (s.top == -1) {
printf("Error: Division without a numerator.\n");
break;
}
double result = calculate(&s);
printf("%.0f %c %.0f = %.0f\n", s.items[s.top - 1].num, op, result, calculate(&s));
} else {
calculate(&s);
}
}
}
return 0;
}
```
这个程序首先读取用户输入的算术表达式,然后逐字符解析,将数字推入栈中,遇到运算符则从栈中弹出最近的操作数进行计算。最后打印出结果。
阅读全文