//二分法和简单迭代法
#include<iostream>
#include<cmath>
#define Length 10
using namespace std;
class Extract {
public:
double fun1(double x);
double fun2(double x);
void input1();
void input2();
int methodofbisection();
int simpleiterationmethod();
void display1();
void display2();
private:
double a;
double b;
double errorvalue;
double init;
double precision;
double root;
}extract;
double Extract::fun1(double x) {
return pow(x, 3) - x - 1;
}
double Extract::fun2(double x) {
return pow(2+4*x, 0.2);
}
void Extract::input1() {
cout << "******************第一题******************" << endl;
double a, b, errorvalue;
cout << " 请输入左区间的值a:";
cin >> a;
cout << " 请输入右区间的值b:";
cin >> b;
cout << " 请输入允许误差ε:";
cin >> errorvalue;
this->a = a;
this->b = b;
this->errorvalue = errorvalue;
}
void Extract::input2() {
int init;
double precision;
cout << "******************第二题******************" << endl;
cout << " 请输入初始值Xo:";
cin >> init;
cout << " 请输入要求的精度:";
cin >> precision;
this->init = init;
this->precision = precision;
}
int Extract::methodofbisection() {
double c=0;
static int num = 0;
for (int n = 0; abs(b-a)>=errorvalue; n++) {
c = a + (b - a) / 2;
if (fun1(c) == 0) {
break;
}else if (fun1(a) * fun1(c) < 0) {
b = c;
}else if(fun1(c) * fun1(b) < 0) {
a = c;
}
num = n;
}
this->root = c;
return num;
}
int Extract::simpleiterationmethod() {
int k=1;
static int num = 0;
double x[Length], r = 0;
x[0] = init;
x[1] = fun2(x[0]);
while (abs(x[k] - x[k - 1]) >= precision) {
k++;
x[k] = fun2(x[k - 1]);
r = x[k];
num = k;
}
root = r;
return num;
}
void Extract::display1() {
cout << " 方程的x^3-x-1=0的根用二分法求得x=" << root << ";" << endl;
cout << " 允许误差ε=" << errorvalue << ",至少需要二分" << methodofbisection() << "次\n" << endl;
}
void Extract::display2() {
cout << " 用简单迭代法求x^5-4x-2=0的近似根为:x=" << root << endl;
cout << " 允许精确度ε=" << precision << ",至少需要迭代" << simpleiterationmethod() << "次" << endl;
cout << endl;
}
int main() {
extract.input1();
extract.methodofbisection();
extract.display1();
extract.input2();
extract.simpleiterationmethod();
extract.display2();
system("pause");
return 0;
}
二分法和简单迭代法的算法的实现
于 2020-11-29 16:30:32 首次发布