Calculator with front and rear ends separated

Student’s information

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentComplete a calculator with front end separation
MU STU ID and FZU STU ID21124337 | 832101212

Assignment Description

This task requires the realization of a fully functional basic calculator, capable of addition, subtraction, multiplication, division and residual operations, and can correctly handle the order of operations. At the same time, the calculator needs to store the user's input and calculation results to the back-end database, and can read and display the user's historical calculation records.

1、PSP form for this work

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning
• Estimate3030
Development
• Analysis3060
• Design Spec2030
• Design Review2030
• Coding Standard2015
• Design60120
• Coding200210
• Code Review3020
• Test6075
Reporting
• Test Report1030
• Size Measurement105
• Postmortem & Process Improvement Plan6070
Sum550695

2、Description of problem-solving ideas

1. Design the User Interface (UI):
    Create a simple and user-friendly UI for the calculator. Include buttons for digits, basic operations, parentheses, and special functions like sin, cos, tan, sqrt, log, and factorial.
    Implement a display area to show the input expression and the result of calculations.

2. Implement Basic Operations:
    Write JavaScript functions for basic arithmetic operations: addition, subtraction, multiplication, division, and remainder (%).
    Implement logic to handle operator precedence and parentheses. You can use the `eval()` function in JavaScript to evaluate expressions.

3. Implement Special Functions:
    Implement functions for trigonometric operations (sin, cos, tan) and other special functions (sqrt, log, factorial). Make sure to handle angle conversion for trigonometric functions.

4. Implement Backend Communication:
    Set up a backend server (using Flask, Django, or any other framework) to handle requests from the calculator.
    Implement endpoints for storing calculations and retrieving history from the database.
    Use XMLHttpRequest or Fetch API in JavaScript to communicate with the backend. Send calculation data to the server when the user performs a calculation.

5. Database Handling:
    Design a database schema to store calculation expressions, results, and timestamps.
    Use appropriate SQL commands to insert new calculations into the database and retrieve the last ten calculations for the history feature.

6. Error Handling:
    Implement error handling to deal with invalid expressions and prevent crashes. Display appropriate error messages to the user.

7. Testing:
    Test the calculator thoroughly to ensure that it handles different types of expressions and special functions correctly.
    Test the communication with the backend to make sure data is stored and retrieved accurately.

8. Documentation and Comments:
    Add comments to your code explaining complex logic and functions.
    Document the API endpoints and their expected request and response formats in your backend code.

9. Styling and User Experience:
    Apply CSS styles to make the calculator visually appealing and user-friendly.
    Ensure a responsive design that works well on both desktop and mobile devices.

3、Design and implementation process.


1.   Planning and Design:
Define Features: List down all the required features, including basic operations, special functions, history tracking, and error handling.
UI/UX Design: Create wireframes or design mockups for the user interface.   Plan the layout of buttons, input area, and result display.
Backend Design: Design the database schema to store calculation history.

2.  Frontend Implementation (HTML/CSS/JavaScript):**
HTML: Create the structure of the calculator interface with buttons and display area.
CSS: Apply styles to buttons, input area, and overall layout.   Ensure responsive design for various screen sizes.
JavaScript:
Implement functions for basic arithmetic operations (+, -, *, /, %).
Implement functions for special operations (sin, cos, tan, sqrt, log, factorial).
Handle input from buttons and update the display area accordingly.
Implement logic to handle parentheses and operator precedence.
Implement the "Ans" button functionality to recall the previous result.
Implement error handling to display appropriate messages for invalid input or operations.

3.   Backend Implementation (Flask/Database):
Flask Setup: Set up Flask framework to handle HTTP requests and responses.
Database Integration: Connect the backend to a database (MySQL, SQLite, etc.).   Implement functions to insert new calculations and retrieve history.
API Endpoints:
Create endpoints for storing new calculations (`/store_calculation`) and retrieving history (`/get_calculation`).
Implement necessary routes and logic to handle these endpoints.

4.   Backend-Frontend Integration:
JavaScript Fetch API/XHR: Implement JavaScript functions to send data (expressions and results) to the backend endpoints using Fetch API or XMLHttpRequest.
Backend Logic: Handle incoming data, store new calculations in the database, and retrieve history as requested.
Frontend Display: Update the frontend UI to display calculation history when the user requests it.

5.   Testing and Debugging:
Unit Testing: Test individual functions for correctness, especially arithmetic and special functions.
Integration Testing: Test the integration between frontend and backend, ensuring data is sent and received correctly.
User Testing: Have users test the calculator for usability and identify any issues.
Debugging: Debug errors, especially those related to invalid input or database interactions.

6.   Documentation and Comments:
Code Comments: Add comments to explain complex logic, especially in the JavaScript functions.
API Documentation: Document the API endpoints, their purposes, expected inputs, and outputs.
User Manual: Create a simple user manual explaining how to use the calculator, special functions, and history features.

7.   Optimization and Refinement:
Performance Optimization: Optimize database queries and frontend code for faster response times.
Refinement: Refine the user interface based on user feedback and usability studies.

 8.Deployment:
Server Deployment: Deploy the backend server and database to a hosting service.
Frontend Hosting: Host the frontend files (HTML, CSS, JavaScript) on a web server.
Domain Configuration: If applicable, configure a custom domain for the calculator.

4、Flowchart 

5、Coding Implementation 

5.1 Front end code

<input class="button" type="button" value="C" onclick="clean()">
<input class="button" type="button" value="←" onclick="back()">
<button class="button" onclick="display('(')">(</button>
<button class="button" onclick="display(')')">)</button>
<input class="button" type="button" value="sqrt" onclick="calculate('sqrt')">
<input class="button" type="button" value="log" onclick="calculate('ln')">
<button class="button" onclick="switchToDeg()">deg</button>
<input class="button" type="button" value="x!" onclick="calculate('x!')">

                <input class="button" type="button" value="sin" onclick="calculate('sin')">
                <input class="button" type="button" value="1" onclick="calculate(1)">
                <input class="button" type="button" value="2" onclick="calculate(2)">
                <input class="button" type="button" value="3" onclick="calculate(3)">
                <input class="button" type="button" value="cos" onclick="calculate('cos')">
                <input class="button" type="button" value="4" onclick="calculate(4)">
                <input class="button" type="button" value="5" onclick="calculate(5)">
                <input class="button" type="button" value="6" onclick="calculate(6)">
                <input class="button" type="button" value="tan" onclick="calculate('tan')">
                <input class="button" type="button" value="7" onclick="calculate(7)">
                <input class="button" type="button" value="8" onclick="calculate(8)">
                <input class="button" type="button" value="9" onclick="calculate(9)">
                <button class="button" onclick="switchToRad()">rad</button>
                <input class="button" type="button" value="." onclick="calculate('.')">
                <input class="button" type="button" value="0" onclick="calculate(0)">
                <input class="button" type="button" value="ans" onclick="gethistory()">

This section of the HTML code represents the buttons and their associated functions in a basic calculator interface. These functions collectively allow users to input numbers, perform basic arithmetic operations, and trigonometric functions, switch between radian and degree modes, and view the previous calculation result.

/* 样式规定了计算器的外观 */

.calculator {
    height: 55px;
    width: 350px;
    background-color: #FAFAD2; /* 设置背景颜色为米色 */
}

/* 按钮的样式 */

.button {
    height: 70px;
    width: 70px;
    color: aliceblue; /* 文本颜色为淡蓝色 */
    font-size: large;
}

/* 显示屏的样式 */

.show {
    display: flex;
    flex-direction: row-reverse;
    height: 50px;
    width: 342px;
    font-size: 2em;
    color: #000000; /* 文本颜色为黑色 */
    margin-top: 7px;
    margin-right: 2px;
}

.form {
    color: #C8C822; /* 文本颜色为浅黄色 */
}

This code sets the style of the calculator buttons and display screen.

function clean(){
    document.form.show.value = ""
}
function sin(){
    equal()
    var jiao = document.form.show.value
    var view =  Math.sin(jiao/180*Math.PI)
    view =view.toFixed(2)
    clean()
    document.form.show.value += view
}
function cos(){
    equal()
    var jiao = document.form.show.value
    var view =  Math.cos(jiao/180*Math.PI)
    view =view.toFixed(2)
    clean()
    document.form.show.value += view
}
function tan(){
    equal()
    var jiao = document.form.show.value
    var view =  Math.tan(jiao/180*Math.PI)
    view =view.toFixed(2)
    clean()
    document.form.show.value += view
}
function back(){
    var t = document.form.show.value
    l = t.length
    document.form.show.value = t.substring(0,l-1)
}
function sqrt(){
    equal()
    document.form.show.value = Math.sqrt(document.form.show.value)
}

The above code implements trigonometric functions and square root as well as backspace and clear functions. 

5.2 Back end code 

# 从请求中获取表达式和结果
    data = request.get_json()
    expression = data.get('expression')
    result = data.get('result')
    current_time = datetime.datetime.now().strftime('%Y.%m.%d %H:%M:%S')# 获取当前时间
    data_tuple = (current_time, expression, result)
    # 插入历史记录到数据库
    insert_query = "INSERT INTO Clark VALUES (%s, %s, %s)"
    cursor.execute(insert_query, data_tuple)
    db_connection.commit()

    response_message = "ok"
    return jsonify({"message": response_message})

The purpose of this code is to receive the expression and the result of the calculation sent by the front end, insert it into the database, and return a response message indicating success.

db_connection = pymysql.connect(
    host='localhost',
    port=3306,
    user='root',
    password='123456',
    database='Gua'
)

app = Flask(__name__)
CORS(app)
cursor = db_connection.cursor()

This code is used to establish a connection to the MySQL database in Python, while initializing a Flask application and a CORS (cross-source Resource Sharing) middleware.

6、Display 

Here is my demo video 

 7、Summary

In this assignment, the task was to create a basic calculator application with specific functionalities.  The project involved implementing various mathematical operations including addition, subtraction, multiplication, division, and remainder.  The calculator also had to support advanced functions like square root, logarithm, trigonometric functions (sin, cos, tan), and factorial calculations.

One crucial requirement was to ensure the correct order of operations and accurate results.  Additionally, the application had to store both the input expression and its result in a backend database.  The history of calculations was retrievable, and the "ans" button allowed users to recall the previous calculation result.

The project required a frontend interface, implemented using HTML, CSS, and JavaScript, where users could input expressions and receive results.  The backend, developed with Python, Flask, and MySQL, managed the calculations, stored history, and provided endpoints for frontend-backend communication.

The problem-solving process involved designing a user-friendly interface, implementing parsing logic for mathematical expressions, handling different types of calculations, and ensuring data integrity with the database.  Error handling was essential, ensuring that if users inputted invalid expressions or attempted operations that could not be performed, appropriate error messages were displayed.

To achieve this, the project was divided into tasks: designing the frontend layout and interactivity, implementing the calculator logic, setting up the backend server, connecting the frontend to the backend, and ensuring data synchronization between the frontend and the database.  Throughout the development process, attention was given to user experience, code modularity, and adherence to best practices.

In summary, the assignment required integrating frontend technologies (HTML, CSS, JavaScript) with backend technologies (Python, Flask, MySQL) to create a functional calculator with a responsive interface.  It provided a comprehensive understanding of web development concepts, data handling, and the coordination between frontend and backend components.

 

Github: ​​​​​​​GitHub - Ayequanhui/assignment2

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值