مثال 2 :
المطلوب :
كتابة دالة تسمى Area ودالة تسمى Volume لحساب مساحة وحجم اسطوانة على الترتيب . ومن ثم كتابة برنامج رئيسى لحساب مساحة وحجم اسطوانة نصف قطرها 2.0cm وارتفاعها 5.0cm . وحفظ المساحة فى المتغير cyl_area والحجم فى المتغير cyl_volume .
الحل :
مساحة الاسطوانة يتم حسابها بواسطة العلاقة :
حيث r و h هما نصف قطر وارتفاع الاسطوانة .
حجم الاسطوانة يتم حسابه بواسطة العلاقة :
فيما يلى الدوال التى تحسب مساحة وحجم الاسطوانة :
كود:
float Area(float radius, float height)
{
float s;
s = 2.0∗PI ∗ radius∗height;
return s;
}
float Volume(float radius, float height)
{
float s;
s = PI ∗radius∗radius∗height;
return s;
}
وفيما يلى البرنامج الرئيسى الذى يقوم بحساب مساحة وحجم اسطوانة نصف قطرها 2.0cm وارتفاعها 5.0cm :
كود:
/∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗
This program calculates the area and volume of a cylinder whose radius is 2.0cm
and height is 5.0cm.
∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗∗/
/∗ Function to calculate the area of a cylinder ∗/
float Area(float radius, float height)
{
float s;
s = 2.0∗PI ∗ radius*height;
return s;
}
/∗ Function to calculate the volume of a cylinder ∗/
float Volume(float radius, float height)
{
float s;
s = PI ∗radius∗radius∗height;
return s;
}
/∗ Start of the main program ∗/
void main()
{
float r = 2.0, h = 5.0;
float cyl_area, cyl_volume;
cyl_area = Area(r, h);
cyl_volume(r, h);
}
مثال 4-3 :