c++ - 问题:“无法将参数 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;
}
解决方案
你在呼唤积分,
cout << "Integral is" << integral(p, -100000, 100000, 1000);
其中 p 不是指向返回 char 并采用 double 的函数的指针
char func(double x);
也许你的意思是定义这样的函数?
推荐阅读
- node.js - 从 NodeJS Express 发送 dist 文件夹中的页面
- azure-devops - 按参数改变 azure devops 管道代理
- javascript - 从 useSelector 获取内容到 setState 而无需两次访问后端
- flutter - 如何在我的 AnimatedWidget 中使用 Flutter 的 Positioned 和 Stack Widget?
- python - 在 Python 中格式化二维码以添加徽标、更改颜色和样式
- google-sheets - 具有联合参数的 Vlookup
- c# - Linq Where 子句根据不同列表的结果生成列表
- android - 地理围栏事件只是用假 gps 应用程序调用,在真正的 gps 中它不会被调用
- python - 在 linux 中使用 selenium headless 拒绝访问
- python - Mongodb 和 Discord.py collection.update_one(update) NameError: name 'update' is not defined 当试图更新 mongodb 集合