網站首頁 編程語言 正文
題目描述
運用多態編寫程序,聲明抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個函數printArea()分別輸出以上三者的面積(結果保留兩位小數),3個圖形的數據在定義對象時給定。
輸入
圓的半徑 矩形的邊長 三角形的底與高
輸出
圓的面積
矩形的面積
三角形的面積
注意:每一行后有回車符
樣例輸入
12.6 4.5 8.4 4.5 8.4
樣例輸出
area of circle=498.76
area of rectangle=37.80
area of triangle=18.90
代碼實現
#include<iostream> #include<iomanip> #define PI 3.1415926 using namespace std; class Shape { public: virtual double printArea()=0; }; class Circle:public Shape { private: double r; public: Circle(double x) { r=x; } virtual double printArea() { return PI*r*r; } }; class Rectangle:public Shape { private: double w,h; public: Rectangle(double x,double y) { w=x,h=y; } virtual double printArea() { return w*h; } }; class Triangle:public Shape { private: double w,h; public: Triangle(double x,double y) { w=x,h=y; } virtual double printArea() { return w*h/2; } }; double printArea(Shape &x) { return x.printArea(); } int main() { double a,b,c,d,e; cin>>a>>b>>c>>d>>e; Circle cir(a); Rectangle rec(b,c); Triangle tri(d,e); cout<<fixed<<setprecision(2)<<"area of circle="<<printArea(cir)<<'\n'; cout<<fixed<<setprecision(2)<<"area of rectangle="<<printArea(rec)<<'\n'; cout<<fixed<<setprecision(2)<<"area of triangle="<<printArea(tri)<<'\n'; return 0; }
原文鏈接:https://blog.csdn.net/qq_44343213/article/details/122251497
相關推薦
- 2023-11-12 ip link set eno2 down后centos無法聯網;centos7.0,二次啟動后無法
- 2022-05-25 kubectl操作命令及使用說明總結_云和虛擬化
- 2022-04-17 小程序 底部懸浮的輸入框聚焦的時候 鍵盤緊貼輸入框
- 2022-11-25 DOS窗口命令和單表簡單查詢_DOS/BAT
- 2022-04-10 用python實現文件備份_python
- 2022-07-21 css實現水平居中和垂直居中,清除浮動
- 2022-04-09 SpringMVC 基礎配置文件(簡潔版本)
- 2022-08-12 Python學習之字典的創建和使用_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支