栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

求矩形的代码(c++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

求矩形的代码(c++)

首先我们要知道矩形的构成元素是啥,长(height),宽(width),这是矩形最基本的两个要素,话不多说,直接上代码。

一:我们首先定义一个类Rectangle

#include 
using namespace std;
class  Rectangle {
private:
    int height;                         //长
    int width;                          //宽
public:
    Rectangle(int height, int width);
    int getZhou();                      //这个函数是用来求周长的
    int getArea();                      //这个函数是用来求面积的
    void print1(int x);
    void print2(int z);
};

然后我们在类外部定义函数

Rectangle::Rectangle(int height , int width) {
    this->height = height;                          //把外部输入的长的值赋值给类内部的长
    this->width = width;                            //把外部输入的宽的值赋值给类内部的宽
}

int Rectangle::getZhou() {
    return (height + width ) * 2;                   //求周长
}

int Rectangle::getArea() {                          //求面积
     return height * width;
}

void Rectangle::print1(int x) {                     //在控制台打印周长的值
    cout << "周长为:" << x << endl;
}

void Rectangle::print2(int z) {                     //在控制台打印面积的值
    cout << "面积为:" << z << endl;
}

二:main方法也就是主函数中的代码

int main() {
    int height;
    int width;
    cout << "请输入长度:" << endl;           //从控制台输入长的值
    cin >> height;
    cout << "请输入宽度:" << endl;           //从控制带输入宽的值
    cin >> width;
    Rectangle Rectangle(height , width);     //把外部输入的长和宽的值赋值给类内部的长和宽
    cout << "******************" << endl;
    cout << "1:求周长" << endl;              //从控制台选择操作
    cout << "2:求面积" << endl;
    cout << "3:结束" << endl;
    cout << "******************" << endl;
    int r = Rectangle.getZhou();             //由类中函数完成,并把周长值导出
    int z = Rectangle.getArea();             //由类中函数完成,并把面积值导出
    while(true){                             //设置一个死循环
        int x;
        cin >> x;
        if ( x == 1){
            Rectangle.print1(r);             //选择1,在控制台打印周长值
        } else if (x == 2){
            Rectangle.print2(z);             //选择2,在控制台打印面积值
        } else if (x == 3){
            break;                           //选择3,结束循环并且结束程序
        }
    }
    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/330370.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号