请用c++语言实现以下要求:1.基于链栈实现简单计算器;2支持加、减、乘、除、求余、括号、次幂等基本操作。3,扩展计算器功能,使其支持 sin、cos、tan、sqrt 等功能
时间: 2023-10-25 20:09:19 浏览: 83
C++代码实现计算器如:加、减、乘、除等简单运算
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct node {
char data;
struct node *next;
} Node, *Stack;
void initStack(Stack *s) {
*s = NULL;
}
int isStackEmpty(Stack s) {
return (s == NULL);
}
void push(Stack *s, char data) {
Node *p = (Node*) malloc(sizeof(Node));
p->data = data;
p->next = *s;
*s = p;
}
char pop(Stack *s) {
char data = (*s)->data;
Node *p = *s;
*s = (*s)->next;
free(p);
return data;
}
char getTop(Stack s) {
return s->data;
}
int priority(char op) {
switch (op) {
case '(':
case ')': return 0;
case '+':
case '-': return 1;
case '*':
case '/':
case '%': return 2;
case '^': return 3;
default: return -1;
}
}
double calculate(double a, double b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
case '%': return fmod(a, b);
case '^': return pow(a, b);
default: return 0;
}
}
double calculateFunc(double x, char func) {
switch (func) {
case 's': return sin(x);
case 'c': return cos(x);
case 't': return tan(x);
case 'q': return sqrt(x);
default: return 0;
}
}
double computeExpression(char *s, int len) {
Stack opStack, numStack;
initStack(&opStack);
initStack(&numStack);
int i = 0;
while (i < len) {
if (s[i] >= '0' && s[i] <= '9') {
double num = s[i] - '0';
i++;
while (i < len && s[i] >= '0' && s[i] <= '9') {
num = num * 10 + (s[i] - '0');
i++;
}
if (i < len && s[i] == '.') {
i++;
double k = 0.1;
while (i < len && s[i] >= '0' && s[i] <= '9') {
num += (s[i] - '0') * k;
k *= 0.1;
i++;
}
}
push(&numStack, num);
} else if (s[i] == 's' || s[i] == 'c' || s[i] == 't' || s[i] == 'q') {
push(&opStack, s[i]);
i += 3;
} else if (s[i] == '(') {
push(&opStack, s[i]);
i++;
} else if (s[i] == ')') {
while (!isStackEmpty(opStack) && getTop(opStack) != '(') {
double b = pop(&numStack);
double a = pop(&numStack);
char op = pop(&opStack);
if (op == 's' || op == 'c' || op == 't' || op == 'q') {
push(&numStack, calculateFunc(b, op));
} else {
push(&numStack, calculate(a, b, op));
}
}
pop(&opStack);
i++;
} else {
while (!isStackEmpty(opStack) && priority(getTop(opStack)) >= priority(s[i])) {
double b = pop(&numStack);
double a = pop(&numStack);
char op = pop(&opStack);
if (op == 's' || op == 'c' || op == 't' || op == 'q') {
push(&numStack, calculateFunc(b, op));
} else {
push(&numStack, calculate(a, b, op));
}
}
push(&opStack, s[i]);
i++;
}
}
while (!isStackEmpty(opStack)) {
double b = pop(&numStack);
double a = pop(&numStack);
char op = pop(&opStack);
if (op == 's' || op == 'c' || op == 't' || op == 'q') {
push(&numStack, calculateFunc(b, op));
} else {
push(&numStack, calculate(a, b, op));
}
}
return pop(&numStack);
}
int main() {
char s[100];
printf("Please enter an expression: ");
scanf("%s", s);
double result = computeExpression(s, strlen(s));
printf("Result: %lf\n", result);
return 0;
}
阅读全文