【无标题】

Course for This Assignmenthttps://bbs.csdn.net/forums/ssynkqtd-04
Assignment Requirementshttps://bbs.csdn.net/topics/617378696
Objectives of This Assignmentimprove the functions of the previous calculator
Other Referenceshttps://www.youtube.com/watch?v=gvRXjsrpCHw&t=40s
MU STU ID and FZU STU ID<832101111_21124728>

Introduction

In this blog post, you will see the process of creating a basic web calculator. This calculator will enable users to perform fundamental arithmetic operations like addition, subtraction, multiplication, nd division. HTML, CSS, and JavaScript are used to construct this project. Also, python is used to create the backend, which based on MySQL, so that the calculator can read the history results.

Interface display

在这里插入图片描述

PSP Form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning2030
• Estimate1010
Development180220
• Analysis120150
• Design Spec2030
• Design Review2020
• Coding Standard1010
• Design120100
• Coding180150
• Code Review2010
• Test1010
Reporting
• Test Repor6060
• Size Measurement3030
• Postmortem & Process Improvement Plan3030
Sum8301010

Code

Link: https://github.com/LoveSerena/calculator

Html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>caculator</title>
    <link rel="stylesheet" href="./css/style.css">
</head>
<body>
    <div class="calculator">
        <input type="text" id="display" readonly>
        <div class="buttons">
            <button onclick="appendToDisplay('tan(')">tan</button>
            <button onclick="calculateScientificNotation()">e^x</button>
            <button onclick="appendToDisplay('sin(')">sin</button>
            <button onclick="appendToDisplay('cos(')">cos</button>
            <button onclick="clearDisplay()">C</button>
            <button onclick="appendToDisplay('7')">7</button>
            <button onclick="appendToDisplay('8')">8</button>
            <button onclick="appendToDisplay('9')">9</button>
            <button onclick="appendToDisplay('+')">+</button>
            <button onclick="appendToDisplay('4')">4</button>
            <button onclick="appendToDisplay('5')">5</button>
            <button onclick="appendToDisplay('6')">6</button>
            <button onclick="appendToDisplay('-')">-</button>
            <button onclick="appendToDisplay('1')">1</button>
            <button onclick="appendToDisplay('2')">2</button>
            <button onclick="appendToDisplay('3')">3</button>
            <button onclick="appendToDisplay('*')">*</button>
            <button onclick="appendToDisplay('.')">.</button>
            <button onclick="appendToDisplay('0')">0</button>
            <button onclick="calculateResult()">=</button>
            <button onclick="appendToDisplay('/')">/</button>
            <button onclick="appendToDisplay('%')">%</button>
            <button onclick="calculateSquareRoot()"></button>
            <button onclick="calculateLog()">log</button>
            <button onclick="addLeftBracket()"> ( </button> 
            <button onclick="addRightBracket()"> ) </button> 
            <button class="ans"onclick="useAns()">ans</button>
          </div>
        </div>
    </div>
    <script src="./js/script.js"></script>
</body>
</html>

This HTML file sets up the structure of our web calculator. It creates a basic webpage with a text input field for displaying results and a container for buttons. The buttons will be dynamically added using JavaScript.

CSS

在这里插body {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.calculator {
    text-align: center;
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    width: 300px; 
}

#display {
    width: 94%;
    padding: 10px;
    font-size: 24px;
    margin-bottom: 10px;
}

.buttons {
    display: grid;
    grid-template-columns: repeat(4, 1fr); 
    grid-template-rows: repeat(6, 1fr); 
    grid-gap: 5px;
}

.buttons button {
    width: 100%;
    height: 50px;
    font-size: 20px;
    margin: 5px;
    cursor: pointer;
}

.buttons .ans {
    width: 200%;
    height: 50px;
    font-size: 20px;
    margin: 5px;
    cursor: pointer;
  }
  入代码片

The CSS file is responsible for styling our web calculator. It defines the visual appearance of the calculator, making it rectangular with a fixed width. It also sets the layout of the buttons using a grid, ensuring they are evenly spaced and have a consistent size.

JavaScript

let display = document.getElementById('display');
let ansValue = 0;

function appendToDisplay(value) {
  display.value += value;
}

function clearDisplay() {
  display.value = '';
}

function calculateResult() {
  try {
    let expression = display.value;

    // Replace trigonometric functions with JavaScript functions
    expression = expression.replace(/sin\(/g, 'Math.sin(');
    expression = expression.replace(/cos\(/g, 'Math.cos(');
    expression = expression.replace(/tan\(/g, 'Math.tan(');


    let result = eval(expression);


    if (!isFinite(result)) {
      display.value = 'Error';
    } else {
      ansValue = result; 
      display.value = result;
    }
  } catch (error) {
    display.value = 'Error';
  }
}

function calculateSquareRoot() {
  display.value = Math.sqrt(eval(display.value));
}

function calculateLog() {
  display.value = Math.log10(eval(display.value));
}

function calculateScientificNotation() {
  display.value = eval(display.value.toExponential());
}

function calculateFactorial() {
  let num = eval(display.value);
  let result = 1;
  for (let i = 2; i <= num; i++) {
    result *= i;
  }
  ansValue = result; 
  display.value = result;
}

function addLeftBracket() {
  display.value += '(';
}

function addRightBracket() {
  display.value += ')';
}


fetch('/history', {
  method: 'GET',
})
  .then(response => response.json())
  .then(data => {
    // 处理获取的历史记录
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
  // 计算结果并发送到后端
function calculateResult() {
  let expression = display.value;

  // 发送POST请求到后端
  fetch('/calculate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ expression: expression }),
  })
    .then(response => response.json())
    .then(data => {
      if (data.error) {
        display.value = 'Error';
      } else {
        ansValue = data.result;
        display.value = data.result;
      }
    })
    .catch(error => {
      console.error('Error:', error);
      display.value = 'Error';
    });
}

// 获取历史记录并显示
function getHistory() {
  // 发送GET请求到后端
  fetch('/history', {
    method: 'GET',
  })
    .then(response => response.json())
    .then(data => {
      // 处理获取的历史记录
      console.log(data);
      // 在前端显示历史记录
      display.value = JSON.stringify(data);
    })
    .catch(error => {
      console.error('Error:', error);
      display.value = 'Error';
    });
}

// 使用答案值
function useAns() {
  display.value += ansValue;
}


The JavaScript file allows the calculator to have some basic functions and can be interacted.The code section from fetch(‘/history’, { … }) is responsible for making an HTTP GET request to a server endpoint (/history) to retrieve historical calculation data. It uses the Fetch API to handle the request and response. The retrieved data is then processed and logged to the console.

Python

from flask import Flask, request, jsonify
import mysql.connector

app = Flask(__name)

# MySQL数据库连接配置
db_config = {
    "host": "127.0.0.1",  # MySQL主机名
    "user": "root",  # MySQL用户名
    "password": "IchLiebeMori",  # MySQL密码
    "database": "calculator_db"  # MySQL数据库名
}

# 创建MySQL数据库连接
conn = mysql.connector.connect(**db_config)
cursor = conn.cursor()

# 创建历史记录表
cursor.execute('''CREATE TABLE IF NOT EXISTS history (
    id INT AUTO_INCREMENT PRIMARY KEY,
    expression TEXT,
    result FLOAT
)''')
conn.commit()

@app.route('/calculate', methods=['POST'])
def calculate():
    data = request.get_json()
    expression = data.get('expression')

    try:
        result = eval(expression)
        store_history(expression, result)
        return jsonify({'result': result})
    except Exception as e:
        return jsonify({'error': str(e)})

@app.route('/history', methods=['GET'])
def get_history():
    cursor.execute("SELECT expression, result FROM history ORDER BY id DESC LIMIT 10")
    history = cursor.fetchall()
    return jsonify(history)

@app.route('/ans', methods=['GET'])
def get_ans():
    cursor.execute("SELECT result FROM history ORDER BY id DESC LIMIT 1")
    ans = cursor.fetchone()
    if ans:
        return jsonify({'ans': ans[0]})
    else:
        return jsonify({'ans': None})

def store_history(expression, result):
    cursor.execute("INSERT INTO history (expression, result) VALUES (%s, %s)", (expression, result))
    conn.commit()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

This Python code sets up a basic Flask web application to handle calculations and store historical data in a MySQL database. It’s designed to be used with a front-end application that sends calculation requests to the /calculate route and retrieves historical data from the /history and /ans routes.

Idea and solution

I chose to make a web calculator using HTML, CSS and JavaScript because it is easy to learn for beginners. choose Python as the backend and MySQL as the database because they are more flexable and easy to perform. What’s more, they are popular and there are a lot of resources for beginners to refer so that if I had any problem, I can find the solution quickly.

Future plan

This calculator now uses a local IP address. In the future, I will deploy the corresponding network service so that this calculator uses the public IP.
More styles may be added to make it more aesthetically pleasing. And more features are also essential.

Conclusion

In this assignment, I learned how to make a backend and use a database. Connecting the front-end and back-end was a big challenge for me, but through various references, I was able to successfully accomplish my goal. From 0 to 1, this assignment made me gain a lot.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值