编程计算图形的面积。程序可计算圆形、长方形、正方形的面积,运行时先提示用户选择图形的类型,然后,对圆形要求用户输入半径值,对长方形要求用户输入长和宽的值,对正方形要求用户输入边长的值,计算出面积的值后将其显示出来。两种方式
时间: 2024-03-22 18:39:34 浏览: 85
图形用户编程.编写一个简单的计算器程序,要求有菜单,能进行简单的加减乘除运算。
5星 · 资源好评率100%
第一种方式:使用Python编写一个控制台程序,实现计算图形面积的功能。代码如下:
```python
import math
print("请选择图形的类型:")
print("1. 圆形")
print("2. 长方形")
print("3. 正方形")
choice = int(input("请输入选项:"))
if choice == 1:
radius = float(input("请输入圆的半径:"))
area = math.pi * radius * radius
print("圆的面积为:", area)
elif choice == 2:
length = float(input("请输入长方形的长度:"))
width = float(input("请输入长方形的宽度:"))
area = length * width
print("长方形的面积为:", area)
elif choice == 3:
side = float(input("请输入正方形的边长:"))
area = side * side
print("正方形的面积为:", area)
else:
print("输入有误,请重新选择")
```
第二种方式:使用Python和Tkinter编写一个图形界面程序,实现计算图形面积的功能。代码如下:
```python
import tkinter as tk
import math
def calculate_area():
choice = shape.get()
if choice == 1:
radius = float(radius_entry.get())
area = math.pi * radius * radius
result_label.config(text="圆的面积为:%.2f" % area)
elif choice == 2:
length = float(length_entry.get())
width = float(width_entry.get())
area = length * width
result_label.config(text="长方形的面积为:%.2f" % area)
elif choice == 3:
side = float(side_entry.get())
area = side * side
result_label.config(text="正方形的面积为:%.2f" % area)
else:
result_label.config(text="请选择图形的类型")
window = tk.Tk()
window.title("图形面积计算器")
shape_label = tk.Label(window, text="请选择图形的类型:")
shape_label.grid(row=0, column=0, padx=10, pady=10, sticky=tk.W)
shape = tk.IntVar()
circle_radiobutton = tk.Radiobutton(window, text="圆形", variable=shape, value=1)
circle_radiobutton.grid(row=1, column=0, padx=10, pady=5, sticky=tk.W)
rectangle_radiobutton = tk.Radiobutton(window, text="长方形", variable=shape, value=2)
rectangle_radiobutton.grid(row=2, column=0, padx=10, pady=5, sticky=tk.W)
square_radiobutton = tk.Radiobutton(window, text="正方形", variable=shape, value=3)
square_radiobutton.grid(row=3, column=0, padx=10, pady=5, sticky=tk.W)
radius_label = tk.Label(window, text="请输入圆的半径:")
radius_label.grid(row=4, column=0, padx=10, pady=5, sticky=tk.W)
radius_entry = tk.Entry(window)
radius_entry.grid(row=4, column=1, padx=10, pady=5)
length_label = tk.Label(window, text="请输入长方形的长度:")
length_label.grid(row=5, column=0, padx=10, pady=5, sticky=tk.W)
length_entry = tk.Entry(window)
length_entry.grid(row=5, column=1, padx=10, pady=5)
width_label = tk.Label(window, text="请输入长方形的宽度:")
width_label.grid(row=6, column=0, padx=10, pady=5, sticky=tk.W)
width_entry = tk.Entry(window)
width_entry.grid(row=6, column=1, padx=10, pady=5)
side_label = tk.Label(window, text="请输入正方形的边长:")
side_label.grid(row=7, column=0, padx=10, pady=5, sticky=tk.W)
side_entry = tk.Entry(window)
side_entry.grid(row=7, column=1, padx=10, pady=5)
calculate_button = tk.Button(window, text="计算面积", command=calculate_area)
calculate_button.grid(row=8, column=0, padx=10, pady=10)
result_label = tk.Label(window, text="")
result_label.grid(row=9, column=0, padx=10, pady=10)
window.mainloop()
```
阅读全文