struct polyTerm { double coef; int exponent; };
struct polyTerm { double coef; int exponent; }; int main() { const int MAX_TERMS = 8; polyTerm poly[MAX_TERMS]; int i, numTerms, exp; double x, value, cf; cout << "\nHow many terms in your polynomial? "; cin >> numTerms; for (i = 0; i < numTerms; i++) { cout << "\nEnter the coefficient for term " << i + 1 << ": "; cin >> cf; cout << "\nEnter exponent for term " << i + 1 << ": "; cin >> exp; poly[i].coef = cf; poly[i].exponent = exp; } cout << "What value of x would you like to evaluate? "; cin >> x; ... ... }
POLYNOMIAL definition: (Algebra) (in one variable) an expression consisting of the sum of two or more terms each of which is the product of a constant and a variable raised to an integral power: 2 ax + bx + c is a polynomial, where a, b, and c are constants and x is a variable. Class example from the C++ code in 321.cpp 2 2 1 0 3x + 1.5x - 121.5 or 3x + 1.5x - 121.5x The constant is called a coefficient. The integral power is called an exponent. Every term has both, except the exponent does not need to be shown when it is 1 or when it is 0.
How many terms is your polynomial? 4 Enter the coefficient for term 1: 10 Enter exponent for term 1: 4 Enter the coefficient for term 2: -3.5 Enter exponent for term 2: 2 Enter the coefficient for term 3: 5 Enter exponent for term 3: 1 Enter the coefficient for term 4: 1000 Enter exponent for term 4: 0 What value of x would you like to evaluate? 2 The value of the polynomial is: 1156 jacobson[weblab]:~$ 4 2 10x - 3.5x + 5x + 1000 4 2 1 0 10x - 3.5x + 5x + 1000x == 1,156 when x == 2.
double evaluate( polyTerm[], int, double); // Compare to your hand-written in class solution double evaluate( polyTerm p[], int n, double x) // You tried developing this in class today. { double pValue = 0; for (int i = 0; i < n; i++) pValue = pValue + p[i].coef * pow(x, p[i].exponent); return pValue; }