pvjc25/du2/program.c

93 lines
2.8 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
// Проверка, является ли строка числом
int je_cislo(const char *str) {
char *endptr;
strtod(str, &endptr);
return *endptr == '\0';
}
// Чтение одного числа с обработкой ошибок
double citaj_cislo(int poradie, int *chyba) {
char buffer[100];
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
if (poradie == 0) {
printf("Nepodarilo sa nacitat zaklad x\n");
} else {
printf("Nepodarilo sa nacitat polynom na %d mieste.\n", poradie);
}
*chyba = 1; // Сообщаем об ошибке
return NAN;
}
char *newline = strchr(buffer, '\n');
if (newline) *newline = '\0'; // Убираем символ новой строки
if (buffer[0] == '\0') {
return NAN; // Пустая строка — конец ввода
}
if (!je_cislo(buffer)) {
if (poradie == 0) {
printf("Nepodarilo sa nacitat zaklad x\n");
} else {
printf("Nepodarilo sa nacitat polynom na %d mieste.\n", poradie);
}
*chyba = 1; // Сообщаем об ошибке
return NAN;
}
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; // Количество коэффициентов
int chyba = 0; // Флаг ошибки
// Считываем x
x = citaj_cislo(0, &chyba);
if (chyba) return 0; // Если ошибка при чтении x, завершаем программу
// Считываем коэффициенты
while (1) {
double koeficient = citaj_cislo(n + 1, &chyba);
if (chyba) return 0; // Если ошибка при чтении коэф., завершаем программу
if (isnan(koeficient)) break; // Пустая строка — конец ввода
koef[n++] = koeficient;
if (n >= 100) {
printf("Chyba: Prilis vela koeficientov.\n");
return 0;
}
}
if (n == 0) {
printf("Chyba: Neboli zadane ziadne koeficienty.\n");
return 0;
}
// Вычисляем результат по схеме Горнера
double vysledok = hornerova_schema(koef, n, x);
printf("Vysledok je: %.2f\n", vysledok);
return 0;
}