After all this time, I FINALLY implemented the calculator!

This commit is contained in:
2024-05-30 17:46:05 +02:00
parent 75410d3a6c
commit eef7bf1aa2
2 changed files with 105 additions and 6 deletions
+104 -5
View File
@@ -1,11 +1,110 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <string.h>
int evalExpr(char* expr, int* res);
int parseTerm(char** ptr);
int parseFactor(char** ptr);
int parseNumber(char** ptr);
// TODO: Parsing doesn't account for addition/subtraction inside brackets, fix that
__attribute__ ((section("entry"))) __attribute__ ((section("entry")))
void main() { void main() {
print("Hello, World!\n"); printf("Welcome to calc.\n");
char in[32]; char input[256];
read(in);
print(in); while (1) {
printf("> ");
read(input);
*strchr(input, '\n') = '\0';
// Remove whitespace
char* old = input;
char* new = input;
while (*old != '\0') {
if (*old == ' ') old++;
*new++ = *old++;
}
*new = '\0';
if (strcmp(input, "exit") == 0) {
break;
}
int res;
if (evalExpr(input, &res)) {
printf("%d\n", res);
} else {
printf("?\n");
}
}
return; return;
} }
int evalExpr(char* expr, int* res) {
char* ptr = expr;
*res = parseTerm(&ptr);
while (*ptr != '\0') {
if (*ptr == '+') {
ptr++;
*res += parseTerm(&ptr);
} else if (*ptr == '-') {
ptr++;
*res -= parseTerm(&ptr);
} else {
return 0; // Invalid
}
}
return 1; // Success
}
int parseTerm(char** ptr) {
int res = parseFactor(ptr);
while (**ptr == '*' || **ptr == '/') {
if (**ptr == '*') {
(*ptr)++;
res *= parseFactor(ptr);
} else if (**ptr == '/') {
(*ptr)++;
int div = parseFactor(ptr);
if (div != 0) {
res /= div;
} else {
return 0;
}
}
}
return res;
}
int parseFactor(char** ptr) {
if (**ptr == '(') {
(*ptr)++;
int res = parseTerm(ptr);
if (**ptr == ')') {
(*ptr)++;
} else {
printf("Error: Missing ')'");
return 0;
}
return res;
} else {
return parseNumber(ptr);
}
}
int parseNumber(char** ptr) {
int res = 0;
while (**ptr >= '0' && **ptr <= '9') {
res *= 10;
res += *(*ptr)++ - '0';
}
return res;
}
+1 -1
View File
@@ -18,7 +18,7 @@ filetable:
db "term16n",0,0,0, "fnt",0,56,4 db "term16n",0,0,0, "fnt",0,56,4
db "testfont",0,0, "fnt",0,60,4 db "testfont",0,0, "fnt",0,60,4
db "test",0,0,0,0,0,0, "txt",0,64,1 db "test",0,0,0,0,0,0, "txt",0,64,1
db "calc",0,0,0,0,0,0, "bin",0,65,2 db "calc",0,0,0,0,0,0, "bin",0,65,6
times 512-($-$$) db 0 times 512-($-$$) db 0