首页 > 解决方案 > 问题:“无法将参数 1 从 'double' 转换为 'char(*)(double)'”

问题描述

我对以下作业有疑问。问题是求函数的积分。它给了我错误“无法将参数 1 从 'double' 转换为 'char(*)(double)'”。我认为问题出在我定义函数的底部。而且我什至不确定是否应该将 char 用于 p。

有谁知道,问题是什么?

/*43. Modify program chapter6_11 to estimate the integral of the function
f (x) = 3x − 2x^2.*/

#include <iostream> //Required for cin, cout
#include <fstream>
#include <cstdlib> //Required for srand(), rand().
#include <cmath> //Required for pow().
using namespace std;

/*-----------------------------------------------------------------*/
/* Program chapter6_11 */
/* */
/* This program finds the real roots of a cubic polynomial */
/* using the Newton-Raphson method. */
double integral(char(p)(double x), double a, double b, double n);

int main(){
    // Declare objects.
    int iterations(0);
    double a1, a2, a3, x, p, dp, tol;
    cout << "Enter coefficients a1, a2, a3 (here -2, 3 and 0)\n";
    cin >> a1 >> a2 >> a3;
    cout << "Enter initial guess for root\n";
    cin >> x;
// Evaluate p at initial guess.
    p =  -2* x * x + 3 * x + 0;
    // Determine tolerance.
    tol = fabs(p);
    while (tol > 0.001 && iterations < 100)
    {
        // Calculate the derivative.
        dp = 2 * -2 * x + 3;
        // Calculate next estimated root.
        x = x - p / dp;
        // Evaluate p at estimated root.
        p = -2 * x * x + 3 * x + 0;
        tol = fabs(p);
        iterations++;
}
if (tol < 0.001)
{
    cout << "Root is " << x << endl;
    cout << iterations << " iterations\n";
    cout << "Integral is" << integral(p, -100000, 100000, 1000);
}
else
cout << "Did not converge after 100 iterations\n";
return 0;
}

double integral(char(p)(double x), double a, double b, double n) {
    double step = (b - a) / n;  // width of each small rectangle
    double area = 0.0;  // signed area
    for (int i = 0; i < n; i++) {
        area += p(a + (i + 0.5) * step) * step; // sum up each small rectangle
    }
    return area;
}

标签: c++argumentsintegral

解决方案


你在呼唤积分,

cout << "Integral is" << integral(p, -100000, 100000, 1000);

其中 p 不是指向返回 char 并采用 double 的函数的指针

char func(double x);

也许你的意思是定义这样的函数?


推荐阅读