This commit is contained in:
Rudolf Zambory 2025-03-07 11:24:15 +01:00
parent 39fdd51cc9
commit 38d1411b97

View File

@ -2,11 +2,19 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <assert.h> #include <assert.h>
#include <ctype.h>
#define LINE_SIZE 100 #define LINE_SIZE 100
#define MAX_COEFFS 100
int horner(int coeffs[], int n, int x) { int is_valid_number(const char *str) {
int result = coeffs[0]; 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++) { for (int i = 1; i < n; i++) {
result = result * x + coeffs[i]; result = result * x + coeffs[i];
} }
@ -15,25 +23,25 @@ int horner(int coeffs[], int n, int x) {
int main() { int main() {
char line[LINE_SIZE]; char line[LINE_SIZE];
memset(line, 0, LINE_SIZE); double coeffs[MAX_COEFFS];
int n = 0;
char* r = fgets(line, LINE_SIZE, stdin); if (fgets(line, LINE_SIZE, stdin) == NULL || !is_valid_number(line)) {
assert(r != NULL); fprintf(stderr, "Error: Invalid input for x.\n");
char* endptr = NULL;
int x = strtol(line, &endptr, 10);
if (endptr == line) {
fprintf(stderr, "Error: Invalid input.\n");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
double x = strtod(line, NULL);
int coeffs[] = {2, 3, 4}; while (fgets(line, LINE_SIZE, stdin) != NULL && line[0] != '\n') {
int n = sizeof(coeffs) / sizeof(coeffs[0]); if (!is_valid_number(line)) {
fprintf(stderr, "Error: Invalid input for coefficient %d.\n", n + 1);
exit(EXIT_FAILURE);
}
coeffs[n++] = strtod(line, NULL);
}
int result = horner(coeffs, n, x); double result = horner(coeffs, n, x);
printf("Vysledok je: %.2f\n", result);
printf("The result of the polynomial evaluation is: %d\n", result);
return 0; return 0;
} }