pvjc24/cv3/program.c

51 lines
1.3 KiB
C
Raw Permalink Normal View History

2024-03-05 13:30:03 +00:00
#include <stdio.h>
#include <stdlib.h>
#define MAX_COEFFICIENTS 100
double evaluate_polynomial(double x, double coefficients[], int degree) {
double result = 0;
for (int i = degree; i >= 0; i--) {
result = result * x + coefficients[i];
}
return result;
}
int main() {
double x;
double coefficients[MAX_COEFFICIENTS];
int degree;
// Read the value of x
if (scanf("%lf", &x) != 1) {
printf("Error: Failed to read the value of x.\n");
return 1;
}
// Read the coefficients of the polynomial
int coefficient_number = 1;
while (scanf("%lf", &coefficients[coefficient_number - 1]) == 1) {
coefficient_number++;
if (coefficient_number > MAX_COEFFICIENTS) {
printf("Error: Too many coefficients.\n");
return 1;
}
}
degree = coefficient_number - 2; // degree of polynomial = number of coefficients - 1
// Check if at least one coefficient is loaded
if (degree < 0) {
printf("Error: No coefficients loaded.\n");
return 1;
}
// Evaluate the polynomial
double result = evaluate_polynomial(x, coefficients, degree);
// Print the result rounded to two decimal places
printf("The output is: %.2lf\n", result);
return 0;
}