pvjc26/du1/program.c
2026-03-04 16:18:56 +01:00

102 lines
1.9 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define SIZE 100
int nacitaj_riadok(double* cislo) {
char riadok[SIZE];
memset(riadok, 0, SIZE);
char* r = fgets(riadok, SIZE, stdin);
if (r == NULL) {
return 0;
}
riadok[strcspn(riadok, "\n")] = '\0';
if (strlen(riadok) == 0) {
return 0;
}
char* koniec = NULL;
long cele_cislo = strtol(riadok, &koniec, 10);
if (koniec == riadok) {
return -1;
}
if (*koniec == '.') {
double desatinne = strtod(riadok, &koniec);
if (koniec == riadok) {
return -1;
}
*cislo = desatinne;
}
else {
*cislo = (double)cele_cislo;
}
return 1;
}
double horner(double* koeficienty, int pocet, double x) {
double vysledok = 0.0;
int i = 0;
for (i = 0; i < pocet; i++) {
vysledok = vysledok * x+ koeficienty[i];
}
return vysledok;
}
int main() {
double h = 0.0;
double koeficienty[SIZE];
int pocet = 0;
memset(koeficienty, 0, SIZE * sizeof(double));
int stav = nacitaj_riadok(&h);
if (stav != 1) {
fprintf(stderr, "Chyba: Nepodarilo sa nacitat hodnotu.\n");
return 1;
}
while (1) {
if (pocet >= SIZE) {
fprintf(stderr, "Chyba: Prilis vela koeficientov (max %d).\n", SIZE);
return 1;
}
double koef = 0.0;
stav = nacitaj_riadok(&koef);
if (stav == 0) {
break;
}
if (stav == -1) {
fprintf(stderr, "Chyba: Nepodarilo sa nacitat koeficient c. %d.\n", pocet + 1);
return 1;
}
koeficienty[pocet] = koef;
pocet += 1;
}
if (pocet == 0) {
fprintf(stderr, "Chyba: Nepodarilo sa nacitat koeficient c. 1.\n");
return 1;
}
double vysledok = horner(koeficienty, pocet, h);
printf("Vysledok je: %.2f\n", vysledok);
return 0;
}