倒单摆22Inverted pendulum)c++代码1201

//倒单摆(Inverted pendulum)c++

#include<stdio.h>

#include<iomanip>

#include <iostream>

#include <cmath>

//#define PI 3.1415926

#define PI 0x3.243F6A8885A3p+0

#define PI16 0x3.243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89p+0

long double fPi0x=atan(1)*4.0;

using namespace std;

class pendulum

{

public:

    double m;    //摆杆的质量

    double l;    //摆杆的长度

    double g;    //重力加速度

    double t;    //时间

    double theta;//摆杆的角度

    pendulum();

    pendulum(double m, double l, double g, double t, double theta);

    double get_theta();

    double get_theta_dot();

    void set_theta_dot(double theta_dot);

    void calculate_theta(double t);

private:

    double theta_dot;//摆杆的角速度

};

pendulum::pendulum()

{

    m = 1.0;

    l = 1.0;

    g = 9.8;

    t = 0.0;

    theta = 0.0;

    theta_dot = 0.0;

}

pendulum::pendulum(double m, double l, double g, double t, double theta)

{

    this->m = m;

    this->l = l;

    this->g = g;

    this->t = t;

    this->theta = theta;

    theta_dot = 0.0;

}

double pendulum::get_theta()

{

    return theta;

}

double pendulum::get_theta_dot()

{

    return theta_dot;

}

void pendulum::set_theta_dot(double theta_dot)

{

    this->theta_dot = theta_dot;

}

void pendulum::calculate_theta(double t)

{

    double a = g / l;

    theta = theta + theta_dot * t + 0.5 * a * t * t;

    theta_dot = theta_dot + a * t;

    if (theta >= 2 * PI)

    {

        theta = theta - 2 * PI;

    }

    else if (theta < 0)

    {

        theta = theta + 2 * PI;

    }

    this->t = t;

}

int main()

{

   

    std::cout << std::setprecision(100);

    std::cout<< fPi0x<<std::endl;

    std::cout<<PI<<std::endl;

    std::cout<<PI16<<std::endl;

    

    pendulum p(1.0, 1.0, 9.8, 0.0, 0.0);

    long double theta, theta_dot;

    

    std::cout << std::setprecision(12);

    for (int i = 0; i < 10; i++)

    {//220for

        theta = p.get_theta();

        theta_dot = p.get_theta_dot();

        p.calculate_theta(0.1);

        

//        printf("t=%ll",p.t);

        cout << "t = " << p.t << ", theta = " << theta << " rad, theta_dot = " << theta_dot << " rad/s" << endl;

//        printf(",theta=%ll",theta);

    }//220for

    return 0;

}//10main

猜你喜欢

转载自blog.csdn.net/aw344/article/details/128439823