C++一天一个程序(五)
(1)確定所求長方形的長和寬。
(2)確定計算長方形的周長和面積的公式并計算。
(3)輸出計算結果。
(1)以面向過程程序設計思想編碼。
#include
using namespace std;
void main(){
int perimeter,area;
int length=20,width=10;
perimeter=2*(length+width);
area=length* width;
cout<<“perimeter=”<<perimeter<<endl;
cout<<“area=”<<area<<endl;
}
2.以面向對象的程序設計方式思考
#include
using namespace std;
class Rectangle
{
public:
Rectangle(float w=0,float 1=0)
{ width=w;length=l; }
void GetArea()
{cout<<’ area="<<widthlength <<endl;}
void GetPerim()
{cout<<“perimeter=”< <2(width+length)<<endl;} private:float width,length;
}
void main()
{
Rectangle a( 10,20);/定義長方形類的個變量 a, 即實例化-個特殊的長方形對象a,它的長是20,寬是
10/
a.GetPerim();//調用a對象的兩個方法
a.GetArea();
}
面向過程注重算法,面向對象注重共同屬性和行為。
總結
以上是生活随笔為你收集整理的C++一天一个程序(五)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++一天一个程序(四)
- 下一篇: 一天一个C++程序(六)