C语言求方程的根的四种算法
Admin
|
2007-12-20 21:07:57
|
TrackRecord:
1319
Times | Tag标签:算法网页
打印本页
您当前所处的位置是:〖首页〗→【文章页】
本站共有16个图文教程栏目,请用心拜读!
本站提供经典的Excel公式函数实例,Word排版技巧,PPT教程;同时更兼有Flash,PowerPoint,数据库等技术文章。
一、迭代法求方程根
/* 迭代法求一个数的平方根 */
#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);
}
会员评论列表:

正在加载数据,请稍后……
针对本篇文章或本站,请您发表个人的建议或批评!