pvjc25/du2/program.c

81 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int je_cislo(const char *str) {
char *endptr;
strtod(str, &endptr);
return *endptr == '\0';
}
double citaj_cislo(int poradie) {
char buffer[100];
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
if (poradie == 0) {
fprintf(stderr, "Chyba: Nepodarilo sa nacitat hodnotu x.\n");
} else {
fprintf(stderr, "Nepodarilo sa nacitat polynom na %d mieste.\n", poradie);
}
exit(1);
}
char *newline = strchr(buffer, '\n');
if (newline) *newline = '\0';
if (buffer[0] == '\0') {
return NAN;
}
if (!je_cislo(buffer)) {
if (poradie == 0) {
fprintf(stderr, "Chyba: Nepodarilo sa nacitat hodnotu x.\n");
} else {
fprintf(stderr, "Nepodarilo sa nacitat polynom na %d mieste.\n", poradie);
}
exit(1);
}
return atof(buffer);
}
double hornerova_schema(double *koef, int n, double x) {
double vysledok = 0.0;
for (int i = 0; i < n; i++) {
vysledok = vysledok * x + koef[i];
}
return vysledok;
}
int main() {
double x;
double koef[100];
int n = 0;
x = citaj_cislo(0);
while (1) {
double koeficient = citaj_cislo(n + 1);
if (isnan(koeficient)) {
break;
}
koef[n++] = koeficient;
if (n >= 100) {
fprintf(stderr, "Chyba: Prilis vela koeficientov.\n");
exit(1);
}
}
if (n == 0) {
fprintf(stderr, "Chyba: Neboli zadane ziadne koeficienty.\n");
return 1;
}
double vysledok = hornerova_schema(koef, n, x);
printf("Vysledok je: %.2f\n", vysledok);
return 0;
}