用C++编程计算图形面积
时间: 2023-11-17 15:08:35 浏览: 180
以下是使用 C++ 编写的计算图形面积的示例程序,其中计算了圆、矩形和三角形的面积:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int choice;
float area;
cout << "Choose a shape to calculate its area:\n";
cout << "1. Circle\n";
cout << "2. Rectangle\n";
cout << "3. Triangle\n";
cin >> choice;
switch(choice)
{
case 1:
{
float radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
area = M_PI * pow(radius, 2);
cout << "The area of the circle is: " << area;
break;
}
case 2:
{
float length, width;
cout << "Enter the length and width of the rectangle: ";
cin >> length >> width;
area = length * width;
cout << "The area of the rectangle is: " << area;
break;
}
case 3:
{
float base, height;
cout << "Enter the base and height of the triangle: ";
cin >> base >> height;
area = 0.5 * base * height;
cout << "The area of the triangle is: " << area;
break;
}
default:
cout << "Invalid choice";
}
return 0;
}
```
在此程序中,我们使用 `switch` 语句根据用户选择的形状来计算面积。根据所选的形状,程序会要求用户输入所需的参数(如圆的半径、矩形的长度和宽度等),并使用相应的公式计算面积。最后,程序将计算出的面积输出到屏幕上。
阅读全文