86 lines
2.8 KiB
C
86 lines
2.8 KiB
C
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdbool.h>
|
|
#include <ctype.h>
|
|
#include <stdlib.h>
|
|
#include <math.h>
|
|
|
|
#define SIZE 50
|
|
|
|
int currentlyInBuffer = 0;
|
|
|
|
bool calculatorLogic(char buffer[SIZE][SIZE]){
|
|
if(isdigit(buffer[currentlyInBuffer][0])){
|
|
if(currentlyInBuffer == 9) {
|
|
printf("full stack\n");
|
|
return false;
|
|
}
|
|
for(int i = 0; i <= currentlyInBuffer; i++){
|
|
if(i == currentlyInBuffer)
|
|
printf("%0.2f \n", roundf(atof(buffer[i])*100)/100);
|
|
else
|
|
printf("%0.2f ", roundf(atof(buffer[i])*100)/100);
|
|
}
|
|
return true;
|
|
}
|
|
else if(strchr("+-/*", buffer[currentlyInBuffer][0]) != NULL){
|
|
if(currentlyInBuffer < 2){
|
|
printf("not enough operands\n");
|
|
return false;
|
|
}
|
|
|
|
double temporaryDecimal = 0;
|
|
|
|
switch(buffer[currentlyInBuffer][0]){
|
|
case '+':
|
|
temporaryDecimal = (double)(round(atof(buffer[currentlyInBuffer-2])*100)/100) + (double)(round(atof(buffer[currentlyInBuffer-1])*100)/100);
|
|
break;
|
|
case '-':
|
|
temporaryDecimal = (double)(round(atof(buffer[currentlyInBuffer-2])*100)/100) - (double)(round(atof(buffer[currentlyInBuffer-1])*100)/100);
|
|
break;
|
|
case '*':
|
|
temporaryDecimal = (double)(round(atof(buffer[currentlyInBuffer-2])*100)/100) * (double)(round(atof(buffer[currentlyInBuffer-1])*100)/100);
|
|
break;
|
|
case '/':
|
|
if(atof(buffer[currentlyInBuffer-1]) == 0.0) {
|
|
printf("division by zero\n");
|
|
return false;
|
|
}
|
|
else
|
|
temporaryDecimal = (double)(round(atof(buffer[currentlyInBuffer-2])*100)/100) / (double)(round(atof(buffer[currentlyInBuffer-1])*100)/100);
|
|
}
|
|
|
|
for(int i = currentlyInBuffer-2; currentlyInBuffer > i; currentlyInBuffer--)
|
|
memset(buffer[currentlyInBuffer], '\0', SIZE);
|
|
|
|
gcvt(temporaryDecimal, 10, buffer[currentlyInBuffer]);
|
|
|
|
for(int i = 0; i <= currentlyInBuffer; i++){
|
|
if(i == currentlyInBuffer)
|
|
printf("%0.2f \n", roundf(atof(buffer[i]) * 100) / 100);
|
|
else
|
|
printf("%0.2f ", roundf(atof(buffer[i]) * 100) / 100);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
else{
|
|
printf("bad input\n");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
char buffer[SIZE][SIZE];
|
|
for(int i = 0; i < SIZE; i++)
|
|
memset(buffer[i], '\0', SIZE);
|
|
|
|
for(; fgets(buffer[currentlyInBuffer], SIZE, stdin); currentlyInBuffer++)
|
|
if(!calculatorLogic(buffer))
|
|
return 0;
|
|
|
|
if(buffer[currentlyInBuffer][0] == '\0')
|
|
printf("no input\n");
|
|
|
|
return 0;
|
|
} |