Обновить du2/program.c

This commit is contained in:
Bohdana Marchenko 2025-03-06 11:07:55 +00:00
parent 13a212c122
commit 8d455bfe3a

View File

@ -5,16 +5,18 @@
#define LINE_SIZE 100
// Funkcia na bezpečné načítanie čísla
// Function to safely read a double value
int read_double(double *value, int coef_index) {
char line[LINE_SIZE];
if (fgets(line, LINE_SIZE, stdin) == NULL) {
return 0; // Chyba pri čítaní
return 0; // Error while reading
}
// Odstránenie nového riadka
// Remove the newline character
line[strcspn(line, "\r\n")] = 0;
// Skontrolujeme, či je riadok prázdny
// Check if the line is empty
if (strlen(line) == 0) {
return 0;
}
@ -22,39 +24,47 @@ int read_double(double *value, int coef_index) {
char *endptr;
*value = strtod(line, &endptr);
// Ak nebolo načítané číslo alebo sú tam neplatné znaky
// If no number was read or there are invalid characters
if (endptr == line || *endptr != '\0') {
printf("Nepodarilo sa nacitat polynom na %d mieste.\n", coef_index); // Zobrazenie správneho indexu
return -1; // Signalizujeme chybu
printf("Nepodarilo sa nacitat polynom na %d mieste.\n", coef_index); // Corrected error message
return -1; // Indicate error
}
return 1;
}
int main() {
double x;
// Read the value of x
if (!read_double(&x, 1)) {
return 1;
}
double coef;
double result = 0;
int coef_count = 1; // Koeficienty začíname indexovať od 1 (pre x^1)
int coef_count = 0; // We will count coefficients starting from 0, so x^0 coefficient will be at index 0
// Loop to read coefficients
while (1) {
int status = read_double(&coef, coef_count + 1); // Tu používame coef_count + 1 pre správny index
coef_count++; // Increase coefficient index for each input
int status = read_double(&coef, coef_count);
if (status == -1) {
return 0; // Očakávané ukončenie pri neplatnom vstupe
return 0; // Exit program if there's invalid input
}
if (status == 0) {
if (coef_count == 1) { // Ak nebol zadaný žiadny koeficient
if (coef_count == 1) { // If no coefficient is provided for x^0
return 1;
}
break;
}
result = result * x + coef;
coef_count++;
result = result * x + coef; // Apply Horner's method for polynomial evaluation
}
// Print the result
printf("Vysledok je: %.2f\n", result);
return 0;
}