使用 switch case 语句查找几何图形面积的 C 程序
cserver side programmingprogramming更新于 2024/11/9 15:35:00
问题
使用 switch case 语句查找矩形、正方形、三角形、圆形的面积, 用户需要在运行时输入底、高、边、半径、宽度和长度来计算所有几何图形的面积。
解决方案
使用 switch case 语句查找矩形、正方形、三角形、圆形面积的解决方案如下 −
公式
查找各个几何图形面积的公式如下 −
- 矩形的面积 = 宽度 * 长度;
- 正方形的面积 = 边 * 边;
- 圆形的面积 = 3.142*radius*radius;
- 三角形的面积 = 0.5 *base*height;
示例
以下是 C 程序,使用 switch case 语句查找矩形、正方形、三角形、圆形的面积 −
#include <stdio.h> void main(){ int fig_code; float side, base, length, breadth, height, area, radius; printf("-------------------------
"); printf(" 1 --> Circle
"); printf(" 2 --> Rectangle
"); printf(" 3 --> Triangle
"); printf(" 4 --> Square
"); printf("-------------------------
"); printf("Enter the Figure code
"); scanf("%d", &fig_code); switch(fig_code){ case 1: printf(" Enter the radius
"); scanf("%f",&radius); area=3.142*radius*radius; printf("Area of a circle=%f
", area); break; case 2: printf(" Enter the breadth and length
"); scanf("%f %f",&breadth, &length); area=breadth *length; printf("Area of a Rectangle=%f
", area); break; case 3: printf(" Enter the base and height
"); scanf("%f %f", &base, &height); area=0.5 *base*height; printf("Area of a Triangle=%f
", area); break; case 4: printf(" Enter the side
"); scanf("%f", &side); area=side * side; printf("Area of a Square=%f
", area); break; default: printf(" Error in figure code
"); break; } }
输出
当执行上述程序时,它会产生以下结果 −
Run 1: ------------------------- 1 --> Circle 2 --> Rectangle 3 --> Triangle 4 --> Square ------------------------- Enter the Figure code 3 Enter the base and height 4 7 Area of a Triangle=14.000000 Run 2: ------------------------- 1 --> Circle 2 --> Rectangle 3 --> Triangle 4 --> Square ------------------------- Enter the Figure code 1 Enter the radius 8 Area of a circle=201.087997