pvjc25/du2/program.c

51 lines
1.1 KiB
C
Raw Normal View History

2025-03-07 10:10:32 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
2025-03-07 10:24:15 +00:00
#include <ctype.h>
2025-03-07 10:10:32 +00:00
#define LINE_SIZE 100
2025-03-07 10:24:15 +00:00
#define MAX_COEFFS 100
2025-03-07 10:10:32 +00:00
2025-03-07 10:24:15 +00:00
int is_valid_number(const char *str) {
char *endptr;
strtod(str, &endptr);
return *endptr == '\0' || isspace(*endptr);
}
2025-03-07 10:39:01 +00:00
double horner(double coeffs[], int n, double x) {
2025-03-07 10:24:15 +00:00
double result = coeffs[0];
2025-03-07 10:10:32 +00:00
for (int i = 1; i < n; i++) {
result = result * x + coeffs[i];
}
return result;
}
int main() {
char line[LINE_SIZE];
2025-03-07 10:24:15 +00:00
double coeffs[MAX_COEFFS];
int n = 0;
2025-03-07 13:08:43 +00:00
2025-03-07 10:24:15 +00:00
if (fgets(line, LINE_SIZE, stdin) == NULL || !is_valid_number(line)) {
fprintf(stderr, "Error: Invalid input for x.\n");
2025-03-07 11:50:37 +00:00
return 1;
2025-03-07 10:10:32 +00:00
}
2025-03-07 10:24:15 +00:00
double x = strtod(line, NULL);
2025-03-07 13:08:43 +00:00
2025-03-07 10:24:15 +00:00
while (fgets(line, LINE_SIZE, stdin) != NULL && line[0] != '\n') {
if (!is_valid_number(line)) {
2025-03-07 11:50:37 +00:00
fprintf(stderr, "Nepodarilo sa nacitat polynom na %d mieste.\n", n + 1);
2025-03-07 13:08:43 +00:00
return 1;
2025-03-07 10:24:15 +00:00
}
coeffs[n++] = strtod(line, NULL);
}
2025-03-07 13:08:43 +00:00
2025-03-07 10:24:15 +00:00
double result = horner(coeffs, n, x);
printf("Vysledok je: %.2f\n", result);
2025-03-07 13:08:43 +00:00
return 0;
2025-03-07 10:10:32 +00:00
}