我一直试图解决这个问题,但没有运气。我要做的就是区分一个多项式,例如P(x) = 3x^3 + 2x^2 + 4x + 5
在代码的末尾,程序应该评估这个函数并给我答案。
的导数P(x)
是P'(x) = 3*3x^2 + 2*2x + 4*1
。如果 x = 1,则答案为 17。无论我如何更改循环,我都无法得到答案。
/*
x: value of x in the polynomial
c: array of coefficients
n: number of coefficients
*/
double derivePolynomial(double x, double c[], int n) {
double result = 0;
double p = 1;
int counter = 1;
for(int i=n-1; i>=0; i--) //backward loop
{
result = result + c[i]*p*counter;
counter++; // number of power
p = p*x;
}
return result;
}
//Output in main() looks like this
double x=1.5;
double coeffs[4]={3,2.2,-1,0.5};
int numCoeffs=4;
cout << " = " << derivePolynomial(x,coeffs,numCoeffs) << endl;