C++ program to calculates the value of a polynomial
#include <iostream.h>
#include <conio.h>
#include <process.h>
const int MAXDEGREE = 10; // define constant
void main()
{
float x, y;
float coefficients[MAXDEGREE+1]; // coefficients of a polynomial
float x_powers[MAXDEGREE+1]; // powers of x
int degree, i;
cout << "\nCalculation of polynomial";
cout << "\nEnter degree ";
cin >> degree;
if (degree > MAXDEGREE || degree < 0)
{
cout << "\nError"; getch(); exit(0);
}
// read coefficients, highest first:
for (i = degree; i >= 0; i--)
{
cout << "\nEnter coefficient " << i << " ";
cin >> coefficients[i];
}
// read x:
cout << "\nEnter x ";
cin >> x;
// calculate powers of x
x_powers[0] = 1;
for (i=1; i <= degree; i++)
{
x_powers[i] = x_powers[i-1] * x;
}
// calculate polynomial
y = 0;
for (i = 0; i <= degree; i++)
{
y = y + coefficients[i] * x_powers[i];
}
// write result
cout << "\n\nResult is " << y;
// wait for key pressure and exit
getch();
}
Related Posts : C++ Programs
0 comments:
Post a Comment