網站首頁 編程語言 正文
題目描述
運用多態編寫程序,聲明抽象基類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-03-20 c#中Invoke與BeginInvoke的用法及說明_C#教程
- 2024-03-03 Element選擇年范圍,year范圍
- 2022-05-28 C++?數據結構超詳細講解單鏈表_C 語言
- 2022-05-11 linq中的連接操作符_實用技巧
- 2022-04-25 C#用NPOI導出導入Excel幫助類_C#教程
- 2022-02-27 VS2010引用全局變量報錯:無法解析的外部符號
- 2022-09-09 OpenSSL生成v3證書方法及配置文件詳解_其它綜合
- 2022-09-16 Pandas缺失值刪除df.dropna()的使用_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同步修改后的遠程分支