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

This commit is contained in:
Bohdana Marchenko 2025-03-06 12:40:33 +00:00
parent c150aeafc0
commit 2989939eb5

View File

@ -5,18 +5,17 @@
#define LINE_SIZE 100 #define LINE_SIZE 100
// Function to safely read a double value
int read_double(double *value, int coef_index) { int read_double(double *value, int coef_index) {
char line[LINE_SIZE]; char line[LINE_SIZE];
if (fgets(line, LINE_SIZE, stdin) == NULL) { if (fgets(line, LINE_SIZE, stdin) == NULL) {
return 0; // Error while reading return 0;
} }
// Remove the newline character
line[strcspn(line, "\r\n")] = 0; line[strcspn(line, "\r\n")] = 0;
// Check if the line is empty
if (strlen(line) == 0) { if (strlen(line) == 0) {
return 0; return 0;
} }
@ -24,10 +23,10 @@ int read_double(double *value, int coef_index) {
char *endptr; char *endptr;
*value = strtod(line, &endptr); *value = strtod(line, &endptr);
// If no number was read or there are invalid characters
if (endptr == line || *endptr != '\0') { if (endptr == line || *endptr != '\0') {
printf("Nepodarilo sa nacitat polynom na %d mieste.\n", coef_index); // Corrected error message printf("Nepodarilo sa nacitat polynom na %d mieste.\n", coef_index);
return -1; // Indicate error return -1;
} }
return 1; return 1;
@ -36,35 +35,33 @@ int read_double(double *value, int coef_index) {
int main() { int main() {
double x; double x;
// Read the value of x
if (!read_double(&x, 1)) { if (!read_double(&x, 1)) {
return 1; return 1;
} }
double coef; double coef;
double result = 0; double result = 0;
int coef_count = 0; // We will count coefficients starting from 0, so x^0 coefficient will be at index 0 int coef_count = 0;
// Loop to read coefficients
while (1) { while (1) {
coef_count++; // Increase coefficient index for each input coef_count++;
int status = read_double(&coef, coef_count); int status = read_double(&coef, coef_count);
if (status == -1) { if (status == -1) {
return 0; // Exit program if there's invalid input return 0;
} }
if (status == 0) { if (status == 0) {
if (coef_count == 1) { // If no coefficient is provided for x^0 if (coef_count == 1) {
return 1; return 1;
} }
break; break;
} }
result = result * x + coef; // Apply Horner's method for polynomial evaluation result = result * x + coef;
} }
// Print the result
printf("Vysledok je: %.2f\n", result); printf("Vysledok je: %.2f\n", result);
return 0; return 0;
} }