C++二分法解方程
/*实现二分法求解方程。编写并使用以下函数:double SolveRoot(double(*pf)(double x),double a,double b,int n)这里,pf指向一个函数f,f用来定义要求解的方程f(x)=0,a和b是未知解x的上下界(即a<=x<=b),n是循环次数。
例如,如果f(x)=x*x-2,则SolveRoot (f,1,2,100)将返回1。414213562373095,即方程为x*x=2的解。二分法的原理是反复地把区间分为两个相等区间,然后用其中含有解的一半代替该区间,依次类推,得到满足精度的解。
它通过检查f(a)和f(b)的符号来判断解是否在区间中。*/#include <cmath>#include <iomanip>#include <iostream>using namespace std;double SolveRoot(double (*pf)(double t), double a, double b, int n){//。
。。
请补充完整 double mid=(a+b)/2; double fm=pf(mid); if(n==0) return mid; double fa=pf(a); if(fm*fa>0) a=mid; else b=mid; return SolveRoot(pf,a,b,n-1);}double f(double x){ return x*x - 2;}int main(){ cout<<setprecision(20); for(int n=10; n<60; n+=5) cout<<"SolveRoot(f,1,2,"<<n<<") = "<<SolveRoot(f,1,2,n)<<endl; cout<<"The exact SolveRoot = "<<sqrt(2)<<endl; return 0;}。
这个程序之适用于你所说的一类方程,其实还要考虑很多情况,如在指定区间根的个数、单调性可能会不同。。
#include <cmath> #include <iomanip> #include <iostream> using namespace std; double SolveRoot(double (*pf)(double t), double a, double b, int n) { double mid=(a+b)/2; if(n==0||pf(mid)==0)return mid; if(pf(mid)*pf(a)>0)return SolveRoot(pf,mid,b,n-1); else return SolveRoot(pf,a,mid,n-1);} double f(double x) { return x*x - 2; } int main() { cout << setprecision(20); for (int n=10; n<100; n+=5) cout << "SolveRoot(f,1,2," << n << ") = " << SolveRoot(f,1,2,n) << endl; cout << "The exact SolveRoot = " << sqrt((double)2) << endl; return 0;}。
#include <cmath> #include <iomanip> #include <iostream> using namespace std; double SolveRoot(double (*pf)(double t), double a, double b, int n) { double m=(a+b)/2; if(n==0) return m; if(pf(m)*pf(a)>0) a=m; else b=m; return SolveRoot(pf,a,b,n-1); } double f(double x) { return x*x - 2; } int main() { cout << setprecision(20); for (int n=10; n<60; n+=5) cout << "SolveRoot(f,1,2," << n << ") = " << SolveRoot(f,1,2,n) << endl; cout << "The exact SolveRoot = " << sqrt(2。
0) << endl; return 0;}。
答:#include float value(float a,float b,float c,float d,float t){ t = a*t*t*t+b*t*...详情>>