From 38d1411b97d8c93666e367a62372a0c405f1ebee Mon Sep 17 00:00:00 2001 From: Rudolf Zambory Date: Fri, 7 Mar 2025 11:24:15 +0100 Subject: [PATCH] 2verzxia --- du2/program.c | 48 ++++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/du2/program.c b/du2/program.c index 2c54c91..eb21f98 100644 --- a/du2/program.c +++ b/du2/program.c @@ -2,11 +2,19 @@ #include #include #include +#include #define LINE_SIZE 100 +#define MAX_COEFFS 100 -int horner(int coeffs[], int n, int x) { - int result = coeffs[0]; +int is_valid_number(const char *str) { + char *endptr; + strtod(str, &endptr); + return *endptr == '\0' || isspace(*endptr); +} + +int horner(double coeffs[], int n, double x) { + double result = coeffs[0]; for (int i = 1; i < n; i++) { result = result * x + coeffs[i]; } @@ -15,25 +23,25 @@ int horner(int coeffs[], int n, int x) { int main() { char line[LINE_SIZE]; - memset(line, 0, LINE_SIZE); - - char* r = fgets(line, LINE_SIZE, stdin); - assert(r != NULL); - - char* endptr = NULL; - int x = strtol(line, &endptr, 10); - - if (endptr == line) { - fprintf(stderr, "Error: Invalid input.\n"); + double coeffs[MAX_COEFFS]; + int n = 0; + + if (fgets(line, LINE_SIZE, stdin) == NULL || !is_valid_number(line)) { + fprintf(stderr, "Error: Invalid input for x.\n"); exit(EXIT_FAILURE); } - - int coeffs[] = {2, 3, 4}; - int n = sizeof(coeffs) / sizeof(coeffs[0]); - - int result = horner(coeffs, n, x); - - printf("The result of the polynomial evaluation is: %d\n", result); - + double x = strtod(line, NULL); + + while (fgets(line, LINE_SIZE, stdin) != NULL && line[0] != '\n') { + if (!is_valid_number(line)) { + fprintf(stderr, "Error: Invalid input for coefficient %d.\n", n + 1); + exit(EXIT_FAILURE); + } + coeffs[n++] = strtod(line, NULL); + } + + double result = horner(coeffs, n, x); + printf("Vysledok je: %.2f\n", result); + return 0; }