C++ I';我是一个初学者,正在尝试编写一个查找数组函数根的函数

C++ I';我是一个初学者,正在尝试编写一个查找数组函数根的函数,c++,arrays,C++,Arrays,我已经工作了几个小时试图找出我做错了什么。我所需要做的就是用牛顿法从一个由数组表示的多项式中找到一个根。这两个函数(polyval和polyder)似乎给了我正确的答案,我觉得主代码正确地执行了牛顿的方法。我希望有经验的人能给我一些建议 #include <iostream> #include <cmath> using namespace std; float polyval(float*, int, float); void polyder(float*, int

我已经工作了几个小时试图找出我做错了什么。我所需要做的就是用牛顿法从一个由数组表示的多项式中找到一个根。这两个函数(polyval和polyder)似乎给了我正确的答案,我觉得主代码正确地执行了牛顿的方法。我希望有经验的人能给我一些建议

#include <iostream>
#include <cmath>

using namespace std;

float polyval(float*, int, float);
void polyder(float*, int, float*);

int main(void)  {
    int n;
    float x=-1,f;
    float tol=pow(10,-5);

    cout << "Enter polynomial order:" << endl;
    cin >> n;

    float* p=new float[n+1];
    float* dp=new float[n];

    cout << "Enter coefficients, starting with the highest power:" << endl;
    for (int k=0;k<n+1;k++) {
        cin >> p[k];
    }

    polyder(p,n,dp);
    f=polyval(p,n,x);

    while (fabs(f)>tol) {
        x=x-f/polyval(dp,n,x);
        f=polyval(p,n,x);
        cout << x << endl;
        cout << f << endl;
    }

    cout << "A real root is at x= " << x << endl;
    cout << "To verify: p(" << x << ") = " << polyval(p,n,x) << endl;

    return 0;
}

float polyval(float* p, int n, float x) {
    float px;
    px=0;

    for (int k=0;k<n+1;k++) {
        px=px+p[k]*pow(x,n-k);
    }

    return px;
}

void polyder(float* p, int n, float* dp) {
    for(int k=0;k<n;k++) {
        dp[k] = p[k+1] * (k+1);
    }
}
#包括
#包括
使用名称空间std;
float polyval(float*,int,float);
void polyder(float*,int,float*);
内部主(空){
int n;
浮动x=-1,f;
浮球tol=功率(10,-5);
cout n;
浮动*p=新浮动[n+1];
浮动*dp=新浮动[n];
库特(托尔){
x=x-f/polyval(dp,n,x);
f=polyval(p,n,x);

不能调用
polyval(dp,n,x)
将访问
dp
的分配空间之外的空间,该空间具有
n
条目,而不是所需的
n+1

如果所有内容都给了您正确的答案,您有什么问题?polyder和polyva函数给了我数字正确的答案。但问题在于主函数si中的某个地方当输入多项式时,x和f的值总是呈指数增长。C++中使用C++的C++中包含了什么?非常感谢!我已经工作了3个小时,试图找出答案,现在终于可以睡了:)使用<代码> STD::向量< /> >和<代码>:
如果不使用c数组和原始指针算法,您的睡眠时间会早得多。