![]() |
#2
mxs8102010-08-13 18:02
|

//用弦截法求方程的根: f(x)= x * x * x - 5 * x * x + 16 * x - 80 (例4_9)
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double f(double); //函数声明
double xpoint(double,double); //函数声明
double root(double,double); //函数声明
int main( )
{
double x1,x2,f1,f2,x;
do
{ cout<< "input x1,x2:";
cin >> x1 >> x2;
f1=f(x1);
f2=f(x2);
} while(f1*f2 >= 0);
x = root(x1,x2);
cout << setiosflags(ios::fixed) << setprecision(7); //指定输出7位小数
cout << "A root of equation is " << x << endl;
return 0;
}
double f(double x) //定义f函数
{ double y;
y = x * x * x - 5 * x * x + 16 * x - 80;
return y;
}
double xpoint(double x1,double x2) //定义spoint 函数,求出弦与 x 轴的交点
{ double y;
y = ( x1 * f(x2) - x2 * f(x1))/(f(x2) - f(x1)); //在 xpoint 函数中调用 f 函数
return y;
}
double root(double x1,double x2) //定义 root 函数,求近似根
{
double x,y,y1;
y1 = f(x1);
do
{ x = xpoint(x1,x2); //在 root 函数中调用 xpoint 函数
y = f(x); //在 root 函数中调用 f 函数
if(y*y1 > 0)
{ y1 = y;
x1 = x;
}
else
x2 = x;
}while(fabs(y)>= 0.00001);
return x;
}
/*
用程序解数学题,要求懂数学知识,在此基础上确定合理的算法,然后设计程序。本程序“算法”见谭浩强《C++程序设计》第一版 P106页。
*/
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
double f(double); //函数声明
double xpoint(double,double); //函数声明
double root(double,double); //函数声明
int main( )
{
double x1,x2,f1,f2,x;
do
{ cout<< "input x1,x2:";
cin >> x1 >> x2;
f1=f(x1);
f2=f(x2);
} while(f1*f2 >= 0);
x = root(x1,x2);
cout << setiosflags(ios::fixed) << setprecision(7); //指定输出7位小数
cout << "A root of equation is " << x << endl;
return 0;
}
double f(double x) //定义f函数
{ double y;
y = x * x * x - 5 * x * x + 16 * x - 80;
return y;
}
double xpoint(double x1,double x2) //定义spoint 函数,求出弦与 x 轴的交点
{ double y;
y = ( x1 * f(x2) - x2 * f(x1))/(f(x2) - f(x1)); //在 xpoint 函数中调用 f 函数
return y;
}
double root(double x1,double x2) //定义 root 函数,求近似根
{
double x,y,y1;
y1 = f(x1);
do
{ x = xpoint(x1,x2); //在 root 函数中调用 xpoint 函数
y = f(x); //在 root 函数中调用 f 函数
if(y*y1 > 0)
{ y1 = y;
x1 = x;
}
else
x2 = x;
}while(fabs(y)>= 0.00001);
return x;
}
/*
用程序解数学题,要求懂数学知识,在此基础上确定合理的算法,然后设计程序。本程序“算法”见谭浩强《C++程序设计》第一版 P106页。
*/