我正在尝试使用二分法求解一个二次方程。尝试评估根时出现此错误:“没有匹配的调用函数”。
#include "assign4.h"
#include <iostream>
using namespace std;
int main(int argc, char * argv[]){
solution s;
double root;
cout << "Enter interval endpoints: ";
cin >> s.xLeft >> s.xRight;
cout << "Enter tolerance: ";
cin >> s.epsilon;
root = s.bisect (s.xLeft, s.xRight, s.epsilon, s.f, s.error);
if (!(s.error))
cout << "Root found at " << root << "\nValue of f(x) at root is: " << s.f(root);
else
cout << "The solution of a quadratic equation with coefficients: " << endl;
cout << "a = " << a << ", b = " << b << ", c = " << c << endl;
cout << "has not been found." << endl;
return 0;
}
错误发生在 root = ... 我的函数 f 似乎有问题但我不明白出了什么问题。下面两段代码是我的类和类实现文件。我们刚刚开始使用类,所以我不确定我的问题是在那里还是只是在上面的代码中。
#ifndef ASSIGN4_H
#define ASSIGN4_H
class solution {
public:
double xLeft, xRight;
double epsilon;
bool error;
double bisect(double, double, double, double f(double), bool&);
double f(double);
};
#endif // ASSIGN4_H
///////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// ////////////
#include "assign4.h"
#include <iostream>
#include <cmath>
using namespace std;
double solution::bisect (double xLeft, double xRight, double epsilon, double func(double), bool& error) {
double xMid;
double fLeft, fRight;
double fMid;
fLeft = f(xLeft);
fRight = f(xRight);
error = (fLeft * fRight) > 0;
if (error)
return -999.0;
while (fabs (xLeft - xRight) > epsilon) {
xMid = (xLeft + xRight) / 2.0;
fMid = f (xMid);
if (fMid == 0.0)
return xMid;
else if (fLeft * fMid < 0.0)
xRight = xMid;
else
xLeft = xMid;
cout << "New Interval is [" << xLeft << ", " << xRight << "]" << endl;
}
return (xLeft + xRight) / 2.0;
}
double solution::f (double x) {
return ((5 * pow(x,2.0)) + (5 * x) + 3);
}