143 lines
3.0 KiB
C
143 lines
3.0 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <math.h>
|
|
#include <ctype.h>
|
|
|
|
#define EPSILON 0.001
|
|
|
|
void trim_newline(char *line) {
|
|
size_t len = strlen(line);
|
|
if (len > 0 && line[len - 1] == '\n') {
|
|
line[len - 1] = '\0';
|
|
}
|
|
}
|
|
|
|
char* skip_spaces(char *str) {
|
|
while (*str && isspace((unsigned char)*str)) {
|
|
str++;
|
|
}
|
|
return str;
|
|
}
|
|
|
|
int parse_expression(char *line, float *num1, char *op, float *num2, float *result) {
|
|
char *ptr = line;
|
|
|
|
ptr = skip_spaces(ptr);
|
|
char *endPtr;
|
|
*num1 = strtof(ptr, &endPtr);
|
|
if (ptr == endPtr) {
|
|
return 1;
|
|
}
|
|
ptr = endPtr;
|
|
|
|
ptr = skip_spaces(ptr);
|
|
if (*ptr == '\0') return 1;
|
|
*op = *ptr;
|
|
if (*op != '+' && *op != '-' && *op != '*' && *op != '/') {
|
|
return 1;
|
|
}
|
|
ptr++;
|
|
|
|
ptr = skip_spaces(ptr);
|
|
*num2 = strtof(ptr, &endPtr);
|
|
if (ptr == endPtr) {
|
|
return 1;
|
|
}
|
|
ptr = endPtr;
|
|
|
|
ptr = skip_spaces(ptr);
|
|
if (*ptr != '=') {
|
|
return 1;
|
|
}
|
|
ptr++;
|
|
|
|
ptr = skip_spaces(ptr);
|
|
*result = strtof(ptr, &endPtr);
|
|
if (ptr == endPtr) {
|
|
return 1;
|
|
}
|
|
ptr = endPtr;
|
|
|
|
ptr = skip_spaces(ptr);
|
|
if (*ptr != '\0') {
|
|
return 1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
float calculate(float num1, char op, float num2, int *error) {
|
|
*error = 0;
|
|
float res;
|
|
switch(op) {
|
|
case '+':
|
|
res = num1 + num2;
|
|
break;
|
|
case '-':
|
|
res = num1 - num2;
|
|
break;
|
|
case '*':
|
|
res = num1 * num2;
|
|
break;
|
|
case '/':
|
|
if (fabs(num2) < EPSILON) {
|
|
*error = 1;
|
|
return 0;
|
|
}
|
|
res = num1 / num2;
|
|
break;
|
|
default:
|
|
*error = 1;
|
|
return 0;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
|
|
void process_line(const char *line, char *output, size_t output_size) {
|
|
char buffer[256];
|
|
strncpy(buffer, line, 255);
|
|
buffer[255] = '\0';
|
|
trim_newline(buffer);
|
|
|
|
float num1, num2, givenResult;
|
|
char op;
|
|
if (parse_expression(buffer, &num1, &op, &num2, &givenResult) != 0) {
|
|
snprintf(output, output_size, "CHYBA");
|
|
return;
|
|
}
|
|
|
|
int calcError = 0;
|
|
float calculatedResult = calculate(num1, op, num2, &calcError);
|
|
if (calcError) {
|
|
snprintf(output, output_size, "ZLE");
|
|
return;
|
|
}
|
|
|
|
float roundedResult = round(calculatedResult * 100) / 100;
|
|
|
|
if (fabs(roundedResult - givenResult) <= EPSILON) {
|
|
snprintf(output, output_size, "OK");
|
|
} else {
|
|
snprintf(output, output_size, "ZLE");
|
|
}
|
|
}
|
|
|
|
|
|
int main(int argc, char *argv[]) {
|
|
char buffer[256];
|
|
char output[32];
|
|
|
|
while (fgets(buffer, sizeof(buffer), stdin) != NULL) {
|
|
trim_newline(buffer);
|
|
if (*skip_spaces(buffer) == '\0') {
|
|
break;
|
|
}
|
|
process_line(buffer, output, sizeof(output));
|
|
printf("%s\n", output);
|
|
}
|
|
|
|
return 0;
|
|
} |