74 lines
1.8 KiB
C
74 lines
1.8 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <ctype.h>
|
|
|
|
#define LINE_SIZE 100
|
|
|
|
// 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; // Error while reading
|
|
}
|
|
|
|
// Remove the newline character
|
|
line[strcspn(line, "\r\n")] = 0;
|
|
|
|
// Check if the line is empty
|
|
if (strlen(line) == 0) {
|
|
return 0;
|
|
}
|
|
|
|
char *endptr;
|
|
*value = strtod(line, &endptr);
|
|
|
|
// If no number was read or there are invalid characters
|
|
if (endptr == line || *endptr != '\0') {
|
|
return -1; // Indicate error
|
|
}
|
|
|
|
return 1;
|
|
}
|
|
|
|
int main() {
|
|
double x;
|
|
|
|
// Read the value of x with special error message for invalid input
|
|
int status = read_double(&x, 1);
|
|
if (status == -1) {
|
|
printf("Nepodarilo sa nacitat zaklad x\n");
|
|
return 1;
|
|
}
|
|
if (status == 0) {
|
|
return 1; // Exit if no input is provided
|
|
}
|
|
|
|
double coef;
|
|
double result = 0;
|
|
int coef_count = 0; // Start counting coefficients from 0
|
|
|
|
// Loop to read coefficients
|
|
while (1) {
|
|
coef_count++; // Increase coefficient index for each input
|
|
status = read_double(&coef, coef_count);
|
|
|
|
if (status == -1) {
|
|
return 0; // Exit program if there's invalid input
|
|
}
|
|
|
|
if (status == 0) {
|
|
if (coef_count == 1) { // If no coefficient is provided for x^0
|
|
return 1;
|
|
}
|
|
break;
|
|
}
|
|
|
|
result = result * x + coef; // Apply Horner's method for polynomial evaluation
|
|
}
|
|
|
|
// Print the result
|
|
printf("Vysledok je: %.2f\n", result);
|
|
return 0;
|
|
} |