【问题标题】:Problem: "Cannot convert argument 1 from 'double' to 'char(*)(double)'"问题:“无法将参数 1 从 'double' 转换为 'char(*)(double)'”
【发布时间】:2020-03-17 10:17:24
【问题描述】:

我对以下作业有疑问。问题是求函数的积分。它给了我错误“无法将参数 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;
}

【问题讨论】:

  • 我认为您应该问自己我要集成什么功能?您遇到问题的原因是您没有编写或选择要集成的功能。显然你不能整合一个数字,这就是错误告诉你的。
  • 顺便说一句,我想你想要double(p)(double x)。对一个区域使用char 没有多大意义。
  • 第一个参数应该是函数指针,但是你传递的是double
  • p 是不是有些价值?而且您正试图将该值与(a + (i + 0.5) * step) 相乘,对吗?如果是这样,您必须像这样使用* 运算符:p * (a + (i + 0.5) * step)。现在在main 中,您将p 声明为double。所以声明不能改变,应该是integral函数中的double p。我看到你以某种方式试图在声明中混合px。同时传递px 怎么样。然后对它们进行一些操作(我不知道p(x) 是什么意思,再次相乘?)并将它们存储在p 中,如下所示:p = p * x
  • 我想知道使用 Newton-Raphson 方法计算多项式的根与积分有什么关系。

标签: c++ arguments integral


【解决方案1】:

你在调用积分,

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

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

char func(double x);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    相关资源
    最近更新 更多