编写一个程序计算图形面积
时间: 2024-05-13 18:14:40 浏览: 21
好的,以下是一个简单的程序,可以计算圆、矩形、三角形的面积。
```python
import math
shape = input("请输入图形的种类(圆、矩形、三角形):")
if shape == "圆":
r = float(input("请输入圆的半径:"))
area = math.pi * r * r
print("圆的面积为:", area)
elif shape == "矩形":
l = float(input("请输入矩形的长:"))
w = float(input("请输入矩形的宽:"))
area = l * w
print("矩形的面积为:", area)
elif shape == "三角形":
b = float(input("请输入三角形的底边长:"))
h = float(input("请输入三角形的高:"))
area = 0.5 * b * h
print("三角形的面积为:", area)
else:
print("输入错误,请输入圆、矩形、三角形中的一种。")
```
你可以根据需要进行修改。
相关问题
编写一个程序计算图形面积引用继成于派生
以下是一个计算图形面积的程序,其中使用了继承和派生的概念:
```c++
#include <iostream>
using namespace std;
class Shape {
protected:
float area;
public:
virtual void calculateArea() = 0; //纯虚函数
float getArea() {
return area;
}
};
class Rectangle : public Shape {
private:
float length;
float width;
public:
Rectangle(float l, float w) {
length = l;
width = w;
}
void calculateArea() {
area = length * width;
}
};
class Circle : public Shape {
private:
float radius;
public:
Circle(float r) {
radius = r;
}
void calculateArea() {
area = 3.14 * radius * radius;
}
};
int main() {
Shape *shape;
Rectangle rectangle(5, 3);
Circle circle(4);
shape = &rectangle;
shape->calculateArea();
cout << "矩形的面积:" << shape->getArea() << endl;
shape = &circle;
shape->calculateArea();
cout << "圆的面积:" << shape->getArea() << endl;
return 0;
}
```
程序中定义了一个抽象类 `Shape`,其中包含一个纯虚函数 `calculateArea()` 和一个成员变量 `area`,表示图形的面积。然后分别定义了两个派生类 `Rectangle` 和 `Circle`,分别用于计算矩形和圆形的面积。在 `main()` 函数中,通过使用基类指针指向不同的派生类对象,实现了对不同图形面积的计算和输出。
编写一个程序计算正方形圆形三角形图形面积
好的,以下是一个Python程序,可以计算正方形、圆形和三角形的面积:
```python
import math
# 计算正方形面积
def square_area(side):
return side * side
# 计算圆形面积
def circle_area(radius):
return math.pi * radius * radius
# 计算三角形面积
def triangle_area(base, height):
return 0.5 * base * height
# 读取用户输入
shape_type = input("请输入图形类型(正方形、圆形或三角形):")
if shape_type == "正方形":
side = float(input("请输入正方形边长:"))
print("正方形面积为:", square_area(side))
elif shape_type == "圆形":
radius = float(input("请输入圆形半径:"))
print("圆形面积为:", circle_area(radius))
elif shape_type == "三角形":
base = float(input("请输入三角形底边长:"))
height = float(input("请输入三角形高:"))
print("三角形面积为:", triangle_area(base, height))
else:
print("不支持的图形类型!")
```
你可以在命令行或者其他Python环境下执行这段代码。它会提示用户输入一个图形类型,然后根据用户输入计算对应图形的面积并输出。注意,这个程序的输入和输出都是英文的。