#include #include //----------------------------------------------------------- // Read a polynomial from stdin. degree is an out parameter. // Format: // degree // c_0 // c_1 // ... // c_degree //----------------------------------------------------------- double* readPolynomial(int* degree) { double* pPoly; int n; if ( 1 != scanf("%d", degree) ) return NULL; pPoly = (double*)malloc( (*degree+1) * sizeof(double) ); if ( !pPoly ) return NULL; // out of memory! for ( n=0; n<=*degree; n++ ) { scanf("%lf", &pPoly[n] ); } return pPoly; } //----------------------------------------------------------- // evaluatePolynomial // returns value of polynomal at x //----------------------------------------------------------- double evaluatePolynomial(double* pPoly, int degree, double x) { int n; double xFactor = 1.0; double result = pPoly[0]; for ( n=1; n<=degree; n++ ) { xFactor *= x; result += pPoly[n]*xFactor; } return result; } //----------------------------------------------------------- // printPolynomial //----------------------------------------------------------- void printPolynomial(double* pPoly, int degree ) { int n; printf("Polynomial: "); for ( n=0; n<=degree && pPoly[n]==0; n++ ); // skip initial elements with 0 coefficient if ( n <= degree ) { if ( n == 0 ) printf(" %lf", pPoly[n]); else printf(" %lfx**%d", pPoly[n], n); for ( n=n+1; n<=degree; n++) { if ( pPoly[n] != 0.0 ) printf(" + %lfx**%d", pPoly[n], n); } } else { printf("0"); } printf("\n"); } //----------------------------------------------------------- // main() // Reads a polynomial and then evaluates it. (End with EOF.) //----------------------------------------------------------- int main(int argc, char* argv[]) { int degree; double* pPoly; double x; while (1) { printf("\nInput a polynomial: "); pPoly = readPolynomial( °ree ); if ( !pPoly ) break; // first, just print it out printf("\n"); printPolynomial( pPoly, degree ); // now sit in loop evaluating it. (End with EOF.) while (1) { printf("x: "); if (1 != scanf("%lf", &x) ) break; printf("%lf\n", evaluatePolynomial(pPoly, degree, x) ); } // done with this polynomial free(pPoly); } return 0; }