import flask
from flask import Flask, render_template, request
# 计算精确的浮点结果,float加法也计算不出来
from decimal import Decimal
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/calculate', methods=['POST'])
# POST请求处理用户提交的数据
def calculate():
num1 = Decimal(request.form['num1'])
num2 = Decimal(request.form['num2'])
operation = request.form['operation']
result = Decimal(0)
# 输入的两个数和运算符,结果初始为0
if operation == 'add':
result = num1 + num2
# 加
elif operation == 'subtract':
result = num1 - num2
# 减
elif operation == 'multiply':
result = num1 * num2
# 乘
elif operation == 'divide':
if num2 != Decimal(0):
result = num1 / num2
else:
return "错误:分母不能为0"
# 除
result = round(result,4)
# 保留四位小数
return render_template('result.html', num1=num1, num2=num2, operation=operation, result=result)
# 然后将计算结果和输入的两个参数返回给result.html渲染
if __name__ == '__main__':
app.run(debug=True)
在线计算器
在线计算器
计算结果
计算结果
{{ num1 }} {{ operation }} {{ num2 }} = {{ result }}
支持小数点计算