ในภาษา C หาพื้นที่วงกลม พื้นที่และปริมาตรทรงกระบอกได้ด้วยโครงสร้าง (struct)
- ตรรกะ พื้นที่วงกลม:
s.areacircle = (float)pi * s.radius * s.radius; - ตรรกะ พื้นที่ทรงกระบอก:
s.areacylinder = (float)2 * pi * s.radius * s.line + 2 * s.areacircle; - ตรรกะ ปริมาตรทรงกระบอก:
s.volumecylinder = s.areacircle * s.line;
อัลกอริทึม
ขั้นตอน 1 - ประกาศสมาชิก struct
ขั้นตอน 2 - ประกาศและกำหนดค่าตัวแปรนำเข้า
ขั้นตอน 3 - ป้อนความสูงและรัศมี
ขั้นตอน 4 - คำนวณพื้นที่วงกลม
ขั้นตอน 5 - คำนวณพื้นที่ทรงกระบอก
ขั้นตอน 6 - คำนวณปริมาตรทรงกระบอก
ตัวอย่าง
โปรแกรม C หาพื้นที่วงกลมและทรงกระบอกด้วย struct:
#include<stdio.h> struct shape{ float line; float radius; float areacircle; float areacylinder; float volumecylinder; }; int main(){ struct shape s; float pi = 3.14; //รับค่าจากผู้ใช้ printf("Enter a length of line or height : "); scanf("%f",&s.line); printf("Enter a length of radius : "); scanf("%f",&s.radius); //พื้นที่วงกลม s.areacircle = (float)pi*s.radius*s.radius; printf("Area of circular cross-section of cylinder : %.2f\n",s.areacircle); //พื้นที่ทรงกระบอก s.areacylinder = (float)2*pi*s.radius*s.line + 2 * s.areacircle; printf("Surface area of cylinder : %.2f\n", s.areacylinder); //ปริมาตรทรงกระบอก s.volumecylinder = s.areacircle*s.line; printf("volume of cylinder : %.2f\n", s.volumecylinder); return 0; }
ผลลัพธ์
Enter a length of line or height: 34 Enter a length of radius: 2 Area of circular cross-section of cylinder: 12.56 Surface area of cylinder: 452.16 volume of cylinder : 427.04