编写计算器程序可以通过多种编程语言实现,以下是使用Python和C语言分别编写简单计算器的步骤和示例代码:
使用Python编写计算器
准备工作
确保已安装Python。
使用Python的Tkinter库,这是Python的标准库,无需额外安装。
基本框架搭建
创建主窗口。
添加显示屏和按钮。
代码实现
导入所需模块。
定义`calculate`函数,根据运算符执行计算。
在主函数中循环接收用户输入,并调用`calculate`函数进行计算。
输出计算结果。
使用C语言编写计算器
准备工作
确保已安装C编译器。
代码实现
包含头文件`stdio.h`。
定义`main`函数。
使用`printf`和`scanf`函数接收用户输入。
根据运算符执行相应的加、减、乘、除操作。
输出计算结果。
示例代码(Python)
```python
import tkinter as tk
from tkinter import ttk
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("计算器")
self.root.geometry("400x600")
self.current_input = ""
self.result_label = tk.Label(root, text="", height=2, anchor="e", font=("Arial", 24))
self.result_label.pack(fill="both", padx=10, pady=10)
self.create_buttons()
def create_buttons(self):
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',
'C'
]
row = 1
col = 0
for button in buttons:
action = lambda x=button: self.on_button_click(x)
ttk.Button(self.root, text=button, command=action, width=5, height=2).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
def on_button_click(self, button):
if button == 'C':
self.current_input = ""
self.result_label.config(text="")
else:
self.current_input += button
self.result_label.config(text=self.current_input)
def calculate(self):
try:
result = eval(self.current_input)
self.result_label.config(text=str(result))
except Exception as e:
self.result_label.config(text="Error: " + str(e))
root = tk.Tk()
calc = Calculator(root)
root.mainloop()
```
示例代码(C语言)