在这个 C 程序中,我们需要找到用户选择的图形的面积。该程序的逻辑是首先声明变量 fig_code 并显示菜单,如下所示:
然后我们需要检查用户输入的是哪种形状,以及如何使用公式来找到相应形状的面积。为了实现这一点,我们使用 switch 语句,程序控制会转到相应的 case,我们应用相应的公式来找到该形状的面积。因此,如果用户输入一个圆形,控制会转到 case 1,并使用公式 3.14* r*r 来找到圆形的面积,对于正方形、矩形或三角形也是如此。最后,在 default case 中,我们将显示一条错误消息。
步骤 1: 包含头文件以在 C 程序中使用内置函数。
步骤 2: 声明整数变量 fig_code 并声明一些 float 变量 side, base, length, breadth, height, Area, radius。
步骤 3: 显示菜单 1. 圆形 2. 矩形 3. 三角形 4. 正方形。
步骤 4: 将图形代码读入变量 fig_code。
步骤 5: 使用 switch 语句检查 fig_code 的值。
步骤 6: 如果 fig_code 为 1,则读取圆的半径并使用公式 3.142*radius*radius 计算面积,然后将圆的面积显示为 Area。
步骤 7: 如果 fig_code 为 2,则读取矩形的宽度和长度,并使用公式 Area=breadth * length 计算面积。然后显示面积。
步骤 8:如果 fig_code 为 3,则读取三角形的底和高,并使用公式 Area=0.5*base * height 计算面积。然后显示面积。
步骤 8: 如果 fig_code 为 4,则读取正方形的边长,并使用公式 area=side*side 计算面积。然后显示面积。
步骤 9: 如果 fig_code 不等于 1、2、3 或 4,我们将显示错误消息。
要查找图形的面积,我们必须使用以下 C 主题,请参阅这些主题以获得更好的理解。
#include <stdio.h>
void main() {
int fig_code;
float side, base, length, breadth, height, area, radius;
printf("-------------------------\n");
printf(" 1 --> Circle\n");
printf(" 2 --> Rectangle\n");
printf(" 3 --> Triangle\n");
printf(" 4 --> Square\n");
printf("-------------------------\n");
printf("Enter the Figure code\n");
scanf("%d", & fig_code);
switch (fig_code) {
case 1:
printf("Enter the radius\n");
scanf("%f", & radius);
area = 3.142 * radius * radius;
printf("Area of a circle=%f\n", area); /* case to find the area of circle */
break;
case 2:
printf("Enter the breadth and length\n");
scanf("%f %f", & breadth, & length);
area = breadth * length;
printf("Area of a Rectangle=%f\n", area); /* case to find area of the rectangle */
break;
case 3:
printf("Enter the base and height\n");
scanf("%f %f", & base, & height);
area = 0.5 * base * height;
printf("Area of a Triangle=%f\n", area); /* case to find the area of the triangle */
break;
case 4:
printf("Enter the side\n");
scanf("%f", & side);
area = side * side;
printf("Area of a Square=%f\n", area); /* case to find area of square */
break;
default:
printf("Error in figure code\n");
break;
} /* End of switch */
} /* End of main() */
Run 1 ------------------------- 1 --> Circle 2 --> Rectangle 3 --> Triangle 4 --> Square ------------------------- Enter the Figure code 2 Enter the breadth and length 2 6 Area of a Rectangle=12.000000 Run 2 ------------------------- 1 --> Circle 2 --> Rectangle 3 --> Triangle 4 --> Square ------------------------- Enter the Figure code 3 Enter the base and height 5 7 Area of a Triangle=17.500000