Dzwebs.Net

撰写电脑技术杂文十余年

C语言求方程的根的四种算法

Admin | 2007-12-20 21:07:57 | 被阅次数 | 16236

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  一、迭代法求方程根

  /* 迭代法求一个数的平方根 */
  #define Epsilon 1.0E-6 /*控制解的精度*/
  #include<math.h>
  main()
  {
  float a,x0,x1;
  printf("请输入要求的数:");
  scanf("%f",&a);
  x0=a/2;
  x1=(x0+a/x0)/2;
  while(fabs(x1-x0)>=Epsilon)
    {
    x0=x1;
    x1=(x0+a/x0)/2;
    }
  printf("%f的平方根:%f.5\n",x1);
  }

  二、求方程根的另一种算法

  #define Epsilon 1.0E-6 /*控制解的精度*/
  #include <stdio.h>
  #include <math.h>
  main()
  {
  float num,pre,this;
  do
    {
    scanf("%f",&num);/*输入要求平方根的数*/
    }while(num<0);
  if (num==0)
    printf("the root is 0");
  else
  {
   this=1;
   do
   {
    pre=this;
    this=(pre+num/pre)/2;
    }while(fabs(pre-this)>Epsilon);/*用解的精度,控制循环次数*/
   }
  printf("the root is %f",this);
  }

  三、用牛顿迭代法

  求方程 2*x*x*x-4*x*x+3*x-6 的根

  /* 牛顿迭代法 */
  #define Epsilon 1.0E-6 /*控制解的精度*/
  #include<math.h>
  main()
  {
   float x1,x0=1.5;
   x1=x0-(2*x0*x0*x0-4*x0*x0+3*x0-6)/(6*x0*x0-8*x0+3);
   while(fabs(x1-x0>=Epsilon)
   {  
      x0=x1;
      x1=x0-(2*x0*x0*x0-4*x0*x0+3*x0-6)/(6*x0*x0-8*x0+3);
   }
   printf("方程的根为%f\n",x1);
  }

  四、用二分法求上题

  /* 二分法 */
  #define Epsilon 1.0E-5 /*控制解的精度*/
  #include<math.h>

  main()
  {
   folat x1,x2,x0,f1,f2,f0;
   x0=(x1+x2)/2;
   f0=2*x0*x0*x0-4*x0*x0+3*x0-6;   /* 求中点的函数值 */
   while(fabs(f0)>=Epsilon)
   {
     if(f0*f1<0)
     { x2=x0;
  f2=2*x2*x2*x2-4*x2*x2+3*x2-6;
     }
     if(f0*f2<0)
     { x1=x0;
  f1=2*x1*x1*x1-4*x1*x1+3*x1-6;
     }
     x0=(x1+x2)/2;
     f0=2*x0*x0*x0-4*x0*x0+3*x0-6;
     }
     printf("用二分法求得方程的根:%f\n",x0);
  }


该杂文来自: 算法杂文

上一篇:C算法之猴子吃桃的程序代码

下一篇:C程序的算法:判断一个数是否为回文数

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计