I was looking in my C textbook and inside there was a page where the prompt told me to translate a polynomial into C code. We have not discussed exponent operators yet and are specifically instructed not to use them at this point and find another way with basic operators. The polynomial goes as such: 5x^(2)+3x-2
.
How do I do this?
Note that ax^2 + bx + c
can be written as
c + x*(b + x*(a))
This can easily be extended to any order of polynomial.
There is no such thing as an exponent operator
in C. While you can accomplish the same thing using pow()
. I suspect your book does not want this. Given this limitation you can do the operation of x^2
as simply x * x
where x
is a variable for your function.
ie You can do something like this:
int poly(int x) {
int y = ((5 * x * x) + (3 * x) - 2);
return y;
}
Addendum:
If you want to have a general formula that you can easily extend for any polynomial degree, you can use this formula instead, with inputs for a
, b
, c
and x
:
int poly(int a, int b, int c, int x) {
int y = c + x*(b + x*(a));
return y;
}
Thanks to chux and FredK for this.
I think you should parameter a,b,c and x in the second polynomial function
int poly2(int a, int b, int c, int x)
{
int y = a*x*x+b*x+c;
return y;
}
when using this function for your case you can call
int result = poly2(a,b,c, x)
with a specific set of a,b,c,x
C doesn't have an exponent operator.
One really handy way to model polynomials is to use an array to store the coefficients, such that the array index corresponds to the power of x
. IOW, to model 5x 2 + 3x - 2
, use
double coef[] = {-2.0, 3.0, 5.0}; // -2.0 + 3.0x + 5.0x^2
To evaluate the polynomial, use a loop, taking into account the property that FredK mentions in his answer - 5x 2 + 3x - 2 == ((5)x + 3)x - 2
:
size_t num_elements = sizeof coef / sizeof coef[0]; // yields 3 in this case
double result = 0;
for (size_t i = num_elements - 1; i > 0; i--)
result += x * ( result + coef[i] );
result += coef[0];
This method will work for polynomials of any degree.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.