c++day2

发布于:2024-04-25 ⋅ 阅读:(19) ⋅ 点赞:(0)
#include <iostream>

using namespace std;
class Rec
{
    double length;
    double width;
public:
    void set_length(int l);
    void set_width(int w);
    int get_length();
    int get_width();
    void show();

};
void Rec::set_length(int l)
{
    length=l;
}
void Rec::set_width(int w)
{
    width=w;
}
int Rec::get_length()
{
    return length;
}
int Rec::get_width()
{

    return width;
}
void Rec::show()
{
    int d=(length+width)*2;
    int s=length*width;
    cout <<"s=" <<s <<endl;
    cout <<"d=" <<d <<endl;

}
int main()
{
            Rec p;
            p.set_length(5);
            p.set_width(2);
            p.get_length();
            p.get_width();
            p.show();
            return 0;
}

计算矩形面积和周长如上图。

2:计算圆的面积和周长

#include <iostream>

using namespace std;
struct yun
{
private:
    double r;
public:
    void set_r(double R);
    void show(double PI=3.14);

};
void yun::set_r(double R)
{
    r=R;
}
void yun::show(double PI)
{
    double D=(2*PI*r);
    double S=PI*r*r;
    cout << "D=" <<D <<endl;
    cout << "S=" <<S <<endl;
}
int main()
{
    yun p1;
    p1.set_r(10);
    p1.show();
    return 0;
}

4:

#include <iostream>

using namespace std;
class Car
{
    string brand;
    string color;
    int speed;
public:
    void display();
    void accelerate(int amout);
    void set(string b,string c,int s);
};
void Car::set(string b,string c,int s)
{
    brand=b;
    color=c;
    speed=s;
}
void Car::accelerate(int amout)
{
    speed+=amout;
    cout <<"speed=" <<speed <<endl;
}
void Car::display()
{
    cout <<"brand=" <<brand <<endl;
    cout <<"color=" <<color <<endl;
    cout <<"speed=" <<speed <<endl;
}
int main()
{
    Car p1;
    p1.set("红旗","红色",100);
    p1.display();
    p1.accelerate(100);
    return 0;
}