爱问知识人 爱问教育 医院库

C 二分法解方程

首页

C++二分法解方程


        

提交回答
好评回答
  • 2008-12-02 15:05:00
      /*实现二分法求解方程。编写并使用以下函数: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;}。

    i***

    2008-12-02 15:05:00

其他答案

    2008-12-02 16:39:00
  •   这个程序之适用于你所说的一类方程,其实还要考虑很多情况,如在指定区间根的个数、单调性可能会不同。。
       #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;}。

    z***

    2008-12-02 16:39:00

  • 2008-11-30 20:05:00
  •   #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;}。

    n***

    2008-11-30 20:05:00

类似问题

换一换

相关推荐

正在加载...
最新问答 推荐信息 热门专题 热点推荐
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200

热点检索

  • 1-20
  • 21-40
  • 41-60
  • 61-80
  • 81-100
  • 101-120
  • 121-140
  • 141-160
  • 161-180
  • 181-200
返回
顶部
帮助 意见
反馈

确定举报此问题

举报原因(必选):