#include <iostream> //stream objects (cin, cout...)
#include <cmath> //math libraries
#include <fstream> //file streaming objects (fstream...)
#include <string> //string manipulation
#include <iomanip> //formatting of output
#include <cstdlib> // need for rand(), srand()
using namespace std;
void get_coeff(double, int, double);
double poly(double ,int, double);
double derivative(double, int, double);
double newton_raphson(double, int, double);
const double PI=acos(-1); //creates a constant for pi
void get_coeff(double a[], int& n, double& xg)
{
cout<<"Please enter the order of the polynomial"<<endl;
cin>>n;
for (int i=0;i<=n; i++)
{
cout<<"a"<<i<<"= ";
cin>>a[n];
}
cout<<"Please enter the first guess= "<<endl;
cin>>xg;
return;
}
double poly(double a[], int n, double xg)
{
double p;
for (int j=0;j<=n;j++)
{
double p= p+a[n]*pow(xg,n);
}
return p;
}
double derivative(double a[], int n, double xg)
{
double dp;
for (int k=0; k<=n; k++)
{
dp=dp+a[n-1]*n*pow(xg,n-1);
}
return dp;
}
double newton_raphson(double a[], int n, double xg)
{
double tol, iterations=0, p, d, x, dp;
tol=fabs(p);
while (tol>0.001 && iterations<100)
{
derivative(a[n], n, xg);
poly(a[n], n, xg);
x=x-p/dp;
tol=fabs(p);
iterations++;
}
if (tol<0.001)
cout<<"x= "<<x<<endl;
else
cout<<"Didn't coverage after 100 iterations"<<endl;
return x;
}
int main() {
int n;
double a[n], xg, p, dp, x;
get_coeff(a[n], n, xg);
newton_raphson(a[n], n, xg);
return 0;
}
为什么一直编译不出来?
是a的数组出错了吗?
#include <cmath> //math libraries
#include <fstream> //file streaming objects (fstream...)
#include <string> //string manipulation
#include <iomanip> //formatting of output
#include <cstdlib> // need for rand(), srand()
using namespace std;
void get_coeff(double, int, double);
double poly(double ,int, double);
double derivative(double, int, double);
double newton_raphson(double, int, double);
const double PI=acos(-1); //creates a constant for pi
void get_coeff(double a[], int& n, double& xg)
{
cout<<"Please enter the order of the polynomial"<<endl;
cin>>n;
for (int i=0;i<=n; i++)
{
cout<<"a"<<i<<"= ";
cin>>a[n];
}
cout<<"Please enter the first guess= "<<endl;
cin>>xg;
return;
}
double poly(double a[], int n, double xg)
{
double p;
for (int j=0;j<=n;j++)
{
double p= p+a[n]*pow(xg,n);
}
return p;
}
double derivative(double a[], int n, double xg)
{
double dp;
for (int k=0; k<=n; k++)
{
dp=dp+a[n-1]*n*pow(xg,n-1);
}
return dp;
}
double newton_raphson(double a[], int n, double xg)
{
double tol, iterations=0, p, d, x, dp;
tol=fabs(p);
while (tol>0.001 && iterations<100)
{
derivative(a[n], n, xg);
poly(a[n], n, xg);
x=x-p/dp;
tol=fabs(p);
iterations++;
}
if (tol<0.001)
cout<<"x= "<<x<<endl;
else
cout<<"Didn't coverage after 100 iterations"<<endl;
return x;
}
int main() {
int n;
double a[n], xg, p, dp, x;
get_coeff(a[n], n, xg);
newton_raphson(a[n], n, xg);
return 0;
}
为什么一直编译不出来?
是a的数组出错了吗?