牛顿迭代方求方程根的公式原理请自行谷歌或百度相关资料,具体代码如下:
// test1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdio.h>
#include<math.h>
#define t_3
//#define t_2
int _tmain(int argc, _TCHAR* argv[])
{
float solution(float a, float b, float c, float d);
float solution1(float a,float b, float c);
float a,b,c,d;
#ifdef t_3
printf("input a,b,c,d:");
scanf("%f,%f,%f,%f", &a,&b,&c,&d);
printf("The solution is: x=%10.7f\n", solution(a,b,c,d));
#else if t_2
printf("input a,b,c:");
scanf("%f,%f,%f", &a,&b,&c);
printf("The solution is: x=%10.7f\n", solution1(a,b,c));
#endif
return 0;
}
float solution(float a,float b, float c,float d)
{
float x=1,x0,f,f1;
do
{
x0=x;
f=((a*x0+b)*x0+c)*x0+d;
f1=(3*a*x0+2*b)*x0+c;
x=x0-f/f1;
}while(fabs(x-x0)>=1e-5);
return x;
}
float solution1(float a,float b, float c)
{
float x=1,x0,f,f1;
do
{
x0=x;
f=(a*x0+b)*x0+c;
f1=(3*a)*x0+b;
x=x0-f/f1;
}while(fabs(x-x0)>=1e-5);
return x;
}
1.求解精度可根据自身情况进行调节,目前精度为1e-5
2.该代码在进行2元一次方程求解时,未考虑负值解。具体2元一次方程求解直接参考http://baike.baidu.com/view/397767.htm?fr=aladdin 求解即可。