二分法和简单迭代法的算法的实现

//二分法和简单迭代法 
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值