C++基础讲义

1、C++对C的扩展

1简单的C++程序

1.1求圆的周长和面积

数据描述:   

                  半径,周长,面积均用实型数表示

数据处理:

                  输入半径 r

                  计算周长 = 2*π*r

                  计算面积 = π* r2 ;

                  输出半径,周长,面积;

方法1:用结构化方法编程,求圆的周长和面积

// count the girth and area of circle

#include<iostream.h>

using name std;

void main ()

{ double r, girth, area ;           

   const double PI = 3.1415 ;

   cout << "Please input radius:\n" ; //操作符重载

   cin >> r ;  //输入

   girth = 2 * PI * r ;

   area = PI * r * r ;

   cout << "radius = " << r << endl ;

   cout << "girth = " << girth << endl ;

   cout << "area = " << area << endl ;

}

 

方法2:用面向对象方法编程,求圆的周长和面积

 

#include<iostream.h>

using name std;

class Circle

{  double radius ; //成员变量

  public : //类的访问控制

    void Set_Radius( double r ) { radius = r ; } //成员函数

    double Get_Radius()  { return  radius ; } //通过成员函数设置成员变量

    double Get_Girth()     { return  2 * 3.14f * radius ; } //通过成员函数获取成员变量

    double Get_Area()     { return  3.14f * radius * radius ; }

} ;

void main()

{

Circle A, B ; //用类定义对象

   A.Set_Radius( 6.23 ) ; //类的调用

   cout << "A.Radius = " << A.Get_Radius() << endl ;

   cout << "A.Girth = " << A.Get_Girth() << endl ;

   cout << "A.Area = " << A.Get_Area() << endl ;

   B.Set_Radius( 10.5 ) ;

   cout << "B.radius = " << B.Get_Radius() << endl ;

   cout << "B.Girth=" << B.Get_Girth() << endl ;

   cout << "B.Area = " << B.Get_Area() << endl ;

}

 

 

总结:建立类、对象、成员变量、成员函数,输入输入流基本概念。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值