Created
April 21, 2016 01:18
-
-
Save lucasmarqs/c25c222060f8365c78cc6e412c763875 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
struct Node { | |
float value; | |
struct Node *next; | |
}; | |
int isNumber(char input[]); | |
void push(float n, struct Node **top); | |
float pop(struct Node **top); | |
void calcNumber(char operator[], struct Node **top); | |
int main() | |
{ | |
struct Node *top; | |
char input[11]; | |
float number; | |
while (strcmp(input, "q") != 0) { | |
scanf("%s", input); | |
if (isNumber(input) == 1) { | |
number = strtof(input, NULL); | |
push(number, &top); | |
} else { | |
calcNumber(input, &top); | |
} | |
} | |
return 0; | |
} | |
void calcNumber(char operator[], struct Node **top) { | |
float n2 = pop(top), n1 = pop(top), result; | |
switch (operator[0]) { | |
case '+': | |
result = n1 + n2; | |
break; | |
case '-': | |
result = n1 - n2; | |
break; | |
case '*': | |
result = n1 * n2; | |
break; | |
case '/': | |
result = n1 / n2; | |
break; | |
} | |
push(result, top); | |
printf("= %f\n", result); | |
} | |
void push(float n, struct Node **top) { | |
struct Node *aux = (struct Node *) malloc(sizeof(struct Node)); | |
aux->value = n; | |
if ((*top) == NULL) { | |
(*top) = aux; | |
(*top)->next = NULL; | |
} else { | |
aux->next = (*top); | |
(*top) = aux; | |
} | |
} | |
float pop(struct Node **top) { | |
if ((*top) == NULL) { | |
printf("Numero insuficiente\n"); | |
exit(0); | |
} | |
float number = (*top)->value; | |
struct Node *aux = (struct Node *) malloc(sizeof(struct Node)); | |
aux = (*top); | |
(*top) = (*top)->next; | |
free(aux); | |
return number; | |
} | |
int isNumber(char input[]) { | |
if (strcmp(input, "+") == 0) { | |
return 0; | |
} else if (strcmp(input, "-") == 0) { | |
return 0; | |
} else if (strcmp(input, "*") == 0) { | |
return 0; | |
} else if (strcmp(input, "/") == 0) { | |
return 0; | |
} else { | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment