您好,登錄后才能下訂單哦!
這篇文章主要介紹“C++如何計(jì)算圓形、矩形和三角形的面積”,在日常操作中,相信很多人在C++如何計(jì)算圓形、矩形和三角形的面積問(wèn)題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”C++如何計(jì)算圓形、矩形和三角形的面積”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!
運(yùn)用多態(tài)編寫(xiě)程序,聲明抽象基類Shape,由它派生出3個(gè)派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個(gè)函數(shù)printArea()分別輸出以上三者的面積(結(jié)果保留兩位小數(shù)),3個(gè)圖形的數(shù)據(jù)在定義對(duì)象時(shí)給定。
圓的半徑 矩形的邊長(zhǎng) 三角形的底與高
圓的面積
矩形的面積
三角形的面積
注意:每一行后有回車符
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; }
到此,關(guān)于“C++如何計(jì)算圓形、矩形和三角形的面積”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。