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 <string.h>
#include <assert.h>
#include <ctype.h>
#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;
}