added calculator

This commit is contained in:
Sven Vogel 2023-09-13 10:27:03 +02:00
parent 4aa1e7a4c1
commit 10780c6e8b
2 changed files with 71 additions and 0 deletions

11
calculator/README.md Normal file
View File

@ -0,0 +1,11 @@
# Simple calculator application
This application asks the user to enter an operator and to two operands. Example:
```
> Enter operator: +
> Enter operand 1: 67
> Enter operand 2: 8
```
It then preceeds to print the result of the calculation:
```
The Result is: 75
```

60
calculator/main.c Normal file
View File

@ -0,0 +1,60 @@
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
// ansi escape codes for colors
#define GREEN "\033[32m"
#define RED "\033[31m"
#define RESET "\033[0m"
int main() {
do {
// allocate memory
double a;
double b;
char op;
printf(GREEN"Enter operator: "RESET);
scanf(" %c", &op); // read character and ignore whitespace
// read operands
printf(GREEN"Enter operand 1: "RESET);
scanf("%lf", &a);
printf(GREEN"Enter operand 2: "RESET);
scanf("%lf", &b);
// result is by default not a number
double res = NAN;
switch (op)
{
case '+':
res = a + b;
break;
case '-':
res = a - b;
break;
case '*':
res = a * b;
break;
case '/':
res = a / b;
break;
default:
printf(RED"invalid operation specified\n"RESET);
break;
}
if (!isnan(res))
{
printf("\nTHE RESULT IS:\n");
char buf[64] = {0};
sprintf(buf, "figlet %lf | lolcat", res);
system(buf);
}
} while(1);
return 0;
}