pvjc25/du2/program.c
2025-02-22 15:30:33 +01:00

59 lines
1.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define maxcoe 100
int read_number (double *num) {
char buffer[50];
if (!fgets(buffer, sizeof(buffer), stdin)) { //если fgets не смог считать строку
return 0;
}
if (sscanf(buffer, "%lf", num) != 1) { //переделываем в double. Если всё успешно
return 0;
}
return 1;
}
double hornerovaschema (double x, double cofecients[], int count) { //вычесляет значение многочлена в точке x
double result = 0.0;
for (int i = 0; i < count; i++) {
result = result * x + cofecients[i];
}
return result;
}
int main() {
double x;
double cof[maxcoe];
int count = 0;
printf("Zadajte x: ");
if (!read_number(&x)) { //если не может считать
printf("Chyba. Nepodarilo sa nacitat hodnotu");
return 1;
}
printf("Zadajte koeficienty (po jednom na riadok, ukoncite prazdnym riadkom):\n");
while (count < maxcoe) {
double coef; //переменна для хранения считанного коэффициента
char buffer[50];//строковый буфер для fgetc
if (!fgets(buffer, sizeof(buffer), stdin) || buffer[0] == '\n') {
break;
}
if (sscanf(buffer, "%lf", &coef) != 1) {
printf("Chyba. Nepodarilo sa nacitat koeficient %d.\n", count + 1);
return 1;
}
cof[count] = coef;
count++;
}
double result = hornerovaschema(x, cof, count);
printf("%.2f\n", result);
return 0;
}