switch case计算面积
时间: 2023-10-18 13:22:57 浏览: 59
以下是一个使用switch case计算不同形状面积的示例代码:
```c++
#include <iostream>
using namespace std;
int main()
{
int shape;
double area, radius, length, width, base, height;
cout << "Enter the shape (1=Circle, 2=Rectangle, 3=Triangle): ";
cin >> shape;
switch(shape)
{
case 1: //Circle
cout << "Enter the radius: ";
cin >> radius;
area = 3.14 * radius * radius;
cout << "Area of circle: " << area << endl;
break;
case 2: //Rectangle
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
area = length * width;
cout << "Area of rectangle: " << area << endl;
break;
case 3: //Triangle
cout << "Enter the base: ";
cin >> base;
cout << "Enter the height: ";
cin >> height;
area = 0.5 * base * height;
cout << "Area of triangle: " << area << endl;
break;
default:
cout << "Invalid shape entered" << endl;
}
return 0;
}
```
在此示例中,用户被要求输入一个数字,以选择要计算面积的形状。根据用户输入的值,switch语句将执行不同的计算,并输出结果。如果用户输入了无效的数字,则会输出错误消息。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)