#include "calculator.h" #include #include #include #include #include // Overenie, či je znak operátor bool je_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'; } // Určenie priority operátorov int priorita(char op) { switch (op) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; default: return 0; } } // Matematické operácie double scitaj(double a, double b) { return a + b; } double odcitaj(double a, double b) { return a - b; } double nasob(double a, double b) { return a * b; } double del(double a, double b) { return a / b; } double sinus(double x) { return sin(x); } double cosinus(double x) { return cos(x); } double odmocnin(double x) { return sqrt(x); } double mocnina(double zaklad, double exponent) { return pow(zaklad, exponent); // Funkcia 'pow' z matematickej knižnice } double logaritmus(double x) { return log(x); } // Funkcia na konverziu infixového výrazu na postfixový (Shunting-yard algoritmus) void infix_na_postfix(const char *infix, char *postfix) { char stack[100]; int top = -1; int j = 0; for (int i = 0; infix[i] != '\0'; i++) { if (isdigit(infix[i]) || infix[i] == '.') { postfix[j++] = infix[i]; } else if (je_operator(infix[i])) { postfix[j++] = ' '; while (top != -1 && priorita(stack[top]) >= priorita(infix[i])) { postfix[j++] = stack[top--]; postfix[j++] = ' '; } stack[++top] = infix[i]; } else if (infix[i] == '(') { stack[++top] = infix[i]; } else if (infix[i] == ')') { while (top != -1 && stack[top] != '(') { postfix[j++] = ' '; postfix[j++] = stack[top--]; } top--; // Odstrániť '(' zo zásobníka } } while (top != -1) { postfix[j++] = ' '; postfix[j++] = stack[top--]; } postfix[j] = '\0'; } // Vyhodnotenie postfixového výrazu double vyhodnot_postfix(const char *postfix) { double stack[100]; int top = -1; char *postfix_copy = malloc(strlen(postfix) + 1); strcpy(postfix_copy, postfix); char *token = strtok(postfix_copy, " "); while (token) { if (isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) { stack[++top] = atof(token); } else if (je_operator(token[0]) && token[1] == '\0') { double b = stack[top--]; double a = stack[top--]; switch (token[0]) { case '+': stack[++top] = scitaj(a, b); break; case '-': stack[++top] = odcitaj(a, b); break; case '*': stack[++top] = nasob(a, b); break; case '/': stack[++top] = del(a, b); break; case '^': stack[++top] = mocnina(a, b); break; } } token = strtok(NULL, " "); } free(postfix_copy); return stack[top]; }