Write a C++ function that evaluates polynomials an a n x n + a n-1 x n-1 , … , a 2 x 2 ,a 1 x 1 , a 0
x 0 . It should take following inputs:
Value of x.
Highest power n.
Coefficients in descending order a n , a n-1 , … , a 2 , a 1 , a 0 (coefficients will ne
n+1)
For instance, if x=4 , n=3 & coefficients are [2,3,1,2], then output should be 182 which is
obtained by evaluating the polynomial 2 * 4 3 + 3 * 4 2 + 1 * 4 1 + 2 * 4 0
Function Prototype: double evaluatePolynomial();
without using array in c++
#include <iostream>
#include <cmath>
using namespace std;
double evaluatePolynomial(double x, int n, double coeff[])
{
double result = 0;
for (int i = n; i >= 0; i--) {
result += coeff[n-i] * pow(x, i);
}
return result;
}
int main()
{
double x = 4;
int n = 3;
double coeff[4] {2, 3, 1, 2};
cout << evaluatePolynomial(x, n, coeff);
return 0;
}
Comments
Leave a comment