calc
This commit is contained in:
parent
5fc2e6455f
commit
0d8d38c2c4
90
du3/program.c
Normal file
90
du3/program.c
Normal file
@ -0,0 +1,90 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ctype.h>
|
||||
|
||||
#define STACK_SIZE 10
|
||||
|
||||
|
||||
struct stack {
|
||||
float values[STACK_SIZE];
|
||||
int size;
|
||||
};
|
||||
|
||||
|
||||
void init(struct stack *s){
|
||||
s->size=0;
|
||||
}
|
||||
|
||||
int is_empty(struct stack *s){return s->size==0;}
|
||||
int is_full(struct stack *s){return s->size==STACK_SIZE-1;}
|
||||
|
||||
|
||||
void push(struct stack *s, float value){
|
||||
if (is_full(s)){
|
||||
printf("Chyba");
|
||||
exit(1);
|
||||
}
|
||||
s->values[s->size++]=value;
|
||||
}
|
||||
|
||||
float pop (struct stack *s){
|
||||
if (is_empty(s)){
|
||||
printf("Stack is empty");
|
||||
return 1;
|
||||
}
|
||||
return s->values[--(s->size)];
|
||||
}
|
||||
|
||||
|
||||
void print_s(struct stack *s){
|
||||
for(int i =0;i<s->size;i++){
|
||||
printf("%.10f ", s->values[i]);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
|
||||
int main(){
|
||||
struct stack mystack;
|
||||
init(&mystack);
|
||||
|
||||
char input[100];
|
||||
|
||||
while(fgets(input, sizeof(input), stdin)){
|
||||
input[strcspn(input,"\n")]='\0';
|
||||
|
||||
char *endpt;
|
||||
float num = strtod(input,&endpt);
|
||||
|
||||
if(endpt!=input&&*endpt=='\0'){
|
||||
push(&mystack,num);
|
||||
}
|
||||
else if (strlen(input)==1&&strchr("+-*/",input[0])){
|
||||
if (mystack.size<2){
|
||||
printf("Nedostatok hodnot");
|
||||
return 1;}
|
||||
float b=pop(&mystack);
|
||||
float a = pop(&mystack);
|
||||
float result = 0;
|
||||
|
||||
if (input[0]=='+') result=a+b;
|
||||
if (input[0]=='-') result=a-b;
|
||||
if (input[0]=='*') result=a*b;
|
||||
if (input[0]=='/'){
|
||||
if (b==0) {printf("delenie nulou, chyba");return 1;}
|
||||
result=a/b;
|
||||
}
|
||||
push(&mystack, result);
|
||||
}
|
||||
else{
|
||||
printf("Chyba");
|
||||
return 1;
|
||||
}
|
||||
print_s(&mystack);
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user