pvjc24/a1/program.c

83 lines
2.1 KiB
C
Raw Normal View History

2024-03-27 13:34:46 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
2024-03-27 14:26:43 +00:00
#include <math.h>
2024-03-27 13:34:46 +00:00
int main() {
char line[100];
double num1, num2, result, expected_result;
char op;
2024-03-27 13:44:36 +00:00
while (fgets(line, sizeof(line), stdin) != NULL) {
if (line[0] == '\n') {
// Stop when the user enters a blank line
break;
}
2024-03-27 14:26:43 +00:00
num1 = num2 = result = expected_result = 0;
2024-03-27 13:44:36 +00:00
op = '\0';
// Remove any spaces between symbols
for (int i = 0; line[i] != '\0'; i++) {
if (isspace(line[i])) {
for (int j = i; line[j] != '\0'; j++) {
line[j] = line[j + 1];
}
i--; // Move back one step to recheck the current character
2024-03-27 13:34:46 +00:00
}
}
2024-03-27 13:44:36 +00:00
// Parse the line
2024-03-27 14:21:51 +00:00
if (sscanf(line, "%lf%c%lf=%lf", &num1, &op, &num2, &expected_result) != 4) {
printf("CHYBA\n");
continue;
}
2024-03-27 13:34:46 +00:00
2024-03-27 13:44:36 +00:00
// Check if the input is valid
if (op != '+' && op != '-' && op != '*' && op != '/') {
printf("CHYBA\n");
continue;
}
2024-03-27 13:34:46 +00:00
2024-03-27 13:44:36 +00:00
// Check for division by zero
if (op == '/' && num2 == 0) {
printf("ZLE\n");
continue;
}
2024-03-27 13:34:46 +00:00
2024-03-27 13:44:36 +00:00
// Perform the calculation
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
2024-03-27 14:26:43 +00:00
if (num2 == 0) {
printf("CHYBA\n");
continue;
}
2024-03-27 13:44:36 +00:00
result = num1 / num2;
break;
}
2024-03-27 13:34:46 +00:00
2024-03-27 14:26:43 +00:00
// Round both result and expected_result to two decimal places
result = round(result * 100.0) / 100.0;
expected_result = round(expected_result * 100.0) / 100.0;
2024-03-27 13:44:36 +00:00
// Check if the result is correct
2024-03-27 14:19:41 +00:00
if (result == expected_result) {
2024-03-27 13:44:36 +00:00
printf("OK\n");
} else {
printf("ZLE\n");
}
2024-03-27 13:34:46 +00:00
}
return 0;
2024-03-27 13:57:38 +00:00
}