Write poly(x, degree, ...) that takes degree + 1 coefficients (highest power first) as doubles and evaluates the polynomial with Horner's method.
Solution
main.c
#include <stdarg.h>
#include <stdio.h>
double poly(double x, int degree, ...) {
va_list ap;
va_start(ap, degree);
double result = 0;
for (int i = 0; i <= degree; i++)
result = result * x + va_arg(ap, double); /* Horner: ((a)x + b)x + c ... */
va_end(ap);
return result;
}
int main(void) {
/* 2x^3 - 6x^2 + 2x - 1 */
for (int x = 0; x <= 3; x++)
printf("p(%d) = %g\n", x, poly(x, 3, 2.0, -6.0, 2.0, -1.0));
return 0;
}
Output Verified by compiling and running
p(0) = -1
p(1) = -3
p(2) = -5
p(3) = 5
Horner's method needs only one multiplication and one addition per coefficient. The coefficients are passed as double literals to match va_arg(ap, double).
More Variable Number of Arguments practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!