- 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)
- html>
- <html>
- <head>
- <title>在线计算器title>
- head>
- <body>
- <h1>在线计算器h1>
- <form action="/calculate" method="POST">
-
- <input type="text" name="num1" required>
- <select name="operation" required>
- <option value="add">+option>
- <option value="subtract">-option>
- <option value="multiply">*option>
- <option value="divide">/option>
-
- select>
- <input type="text" name="num2" required>
- <button type="submit">开始计算button>
-
- form>
- body>
- html>
- html>
- <html>
- <head>
- <title>计算结果title>
- head>
- <body>
- <h1>计算结果h1>
- <p>{{ num1 }} {{ operation }} {{ num2 }} = {{ result }}p>
-
- body>
- html>
支持小数点计算