Print the Result
In this final step, you will enhance the polynomial evaluation program by adding formatted output and error handling to improve the user experience.
Open the previous C file and update it with improved result printing:
cd ~/project
nano polynomial_eval.c
Update the code with formatted result printing and input validation:
#include <stdio.h>
#define MAX_DEGREE 10
double hornerMethod(int degree, double coefficients[], double x) {
double result = coefficients[degree];
for (int i = degree - 1; i >= 0; i--) {
result = result * x + coefficients[i];
}
return result;
}
void printPolynomial(int degree, double coefficients[]) {
printf("Polynomial: ");
for (int i = degree; i >= 0; i--) {
if (coefficients[i] != 0) {
if (i == degree) {
printf("%.2fx^%d ", coefficients[i], i);
} else if (i > 1) {
printf("%+.2fx^%d ", coefficients[i], i);
} else if (i == 1) {
printf("%+.2fx ", coefficients[i]);
} else {
printf("%+.2f", coefficients[i]);
}
}
}
printf("\n");
}
int main() {
int degree;
double coefficients[MAX_DEGREE + 1];
double x, result;
// Input validation
do {
printf("Enter the degree of the polynomial (0-10): ");
scanf("%d", °ree);
} while (degree < 0 || degree > MAX_DEGREE);
printf("Enter coefficients from highest degree to constant term:\n");
for (int i = degree; i >= 0; i--) {
printf("Coefficient for x^%d: ", i);
scanf("%lf", &coefficients[i]);
}
printf("Enter the value of x: ");
scanf("%lf", &x);
// Print polynomial details
printPolynomial(degree, coefficients);
// Evaluate polynomial using Horner's method
result = hornerMethod(degree, coefficients, x);
// Formatted result output
printf("Polynomial Evaluation:\n");
printf("P(x) = f(%.2f) = %.2f\n", x, result);
return 0;
}
Compile and run the updated program:
gcc polynomial_eval.c -o polynomial_eval
./polynomial_eval
Example output:
Enter the degree of the polynomial (0-10): 3
Enter coefficients from highest degree to constant term:
Coefficient for x^3: 2
Coefficient for x^2: -3
Coefficient for x^1: 0
Coefficient for x^0: 5
Enter the value of x: 2
Polynomial: 2.00x^3 -3.00x^2 +5.00
Polynomial Evaluation:
P(x) = f(2.00) = 11.00
Key improvements:
- Added
printPolynomial()
function to display the polynomial
- Implemented input validation for polynomial degree
- Enhanced result printing with formatted output
- Showing both the polynomial and its evaluated value