C++算例 0001

一、弦截法求方程根

二、算法(见教材)

三、编程实现

/*
(1)代码中用函数发f(x)代表x的函数
(2)用函数xpoint(x1,x2)来求(x1,f(x1))和(x2,f(x2))的连线与x轴的交点x的坐标。
(3)用函数root(x1,x2)来求(x1,x2)区间的那个实根。 
*/
#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);
        if (f1*f2>=0)
           cout<<"f1,f2同符号,继续取值:\n";
        else
            break;
    }while(f1*f2>=0); //当f1、f2的乘积为正值时,说明条件不满足,需要进一步确定x1,x2的取值 
    cout<<"f1,f2取值符合条件,开始计算函数根:\n";
    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函数,以实现f(x) 
{
    double y;
    y=x*x*x-6*x*x+16*x-80;
    return y;
}

double xpoint(double x1, double x2)
{
    double y;
    y=(x1*f(x2)-x2*f(x1))/(f(x2)-f(x1));
    return y;

double root(double x1, double x2)
{
    double x,y,y1;
    y1=f(x1);
    do
    {
        x=xpoint(x1,x2);
        y=f(x);
        if(y*y1>0)
        {
            y1=y;
            x1=x;
        }
        else
          x2=x;
    }while(fabs(y)>=0.00001);
    return x;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值