Assignment2

EE301 Calculator

Personal information

The Link My Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentUsing front-end and back-end technology to create a scientific calculator, this calculator can not only perform basic operations but also perform high-order function operations. At the same time, it also has the function of querying historical records.
MU STU ID and FZU STU ID21125309_832102209
The Link of Code of this assignment of GitHubhttps://github.com/Eminem12304/assignment2-1

catalogue

1.Project introduction
2. Personal Software Process (PSP) Form
3. Work introduction

1.Project introduction
In the previous project, I used front-end technology to implement a basic calculator (which can achieve addition, subtraction, multiplication, and division). This time, I have implemented more functions on top of the original calculator. For example, taking remainder, trigonometric functions, parenthesis operations, exponential operations, power operations, root sign operations, etc. Simultaneously utilizing the combination of front-end and back-end technology, the calculator has achieved the function of querying historical records.

2. Personal Software Process (PSP) Form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning(total)60100
• Estimate60100
Development(total)560645
• Analysis6090
• Design Spec3060
• Design Review6045
• Coding Standard4530
• Design6075
• Coding200220
• Code Review6065
• Test4560
Reporting(total)90105
• Test Repor3045
• Size Measurement3020
• Postmortem & Process Improvement Plan3040
Sum710850

3. Work introduction
UI display
在这里插入图片描述

Basic operations

20231022-191549

Parenthesis operation and taking remainder

20231022-192506

Trigonometric function operation

20231022-194656

Power and Exponential Operations

20231022-195923

Radical operation

20231022-214047

Query History Function

20231022-233030

4. Ideas for solving problems
After receiving this assignment, the first thing I confirmed was to continue the previous assignment and use HTML+CSS+JavaScript to write the calculator front-end page and its basic functions. In terms of databases, after a period of understanding, I have decided to use MySQL, and the language I am proficient in is Java.

HTML5+CSS+JS advantage lies in

  • HTML5 gives web pages better meaning and structure. More diverse tags will be built with support for RDFa, microdata, and microformats, creating a data-driven web that is more valuable for both programs and users.

  • The web app developed based on HTML5 has shorter startup time and faster networking speed, all thanks to the HTML5 APP Cache and local storage function. Indexed DB (one of the most important technologies for html5 local storage) and API documentation.

  • Before the arrival of HTML5, due to the diversity of platforms, it was necessary to develop multiple versions for different platforms for each set of products, which consumed a lot of time and effort, and also increased development costs. However, the emergence of HTML5 technology can effectively solve this problem. As long as developers use one set of programs, they can easily achieve the presentation functions of multiple platforms, reducing development difficulty, Saves development time and cost investment.

  • The coolest feature in HTML5 is offline caching. JavaScript provides several different offline storage functions, which have better flexibility and architecture compared to traditional cookies, and can store more content. It has better security and performance, and can be saved even after the browser is closed.

  • Previously, when native applications were launched on the Appstore, they had to wait for a long review time. If there were any issues that needed to be updated, they had to be re reviewed, which invisibly wasted a lot of time. HTML5 is loaded through a browser, so there is no such issue. If any problems occur, it can be updated and launched in a timely manner without waiting for review time.

MySQL advantage lies in
Using MySQL also has many advantages:

  • Fast running speed, small MySQL size, and fast command execution speed.

  • Low usage cost. MySQL is open source and provides a free version, greatly reducing usage costs for most users.

  • Easy to use. Compared to the setup and management of other large databases, it has lower complexity and is easy to use.

  • Strong portability. MySQL can run on various system platforms, such as Windows, Linux, Unix, etc.

  • Suitable for more users. MySQL supports the most commonly used data management functions and is suitable for small and medium-sized enterprises and even large website applications.

5.Steps to solve the problem

Implementation process:
MySQL is a relational database management system, while HTML is a markup language used to build web pages. In web development, the interaction between MySQL and HTML is usually achieved through the use of server-side programming languages such as PHP, Python, Java, etc. The following is the general process of interaction between MySQL and HTML:
1.The client (browser) sends HTTP requests to the server.
2.After receiving the request, the server connects to the MySQL database using a server-side programming language such as PHP.
3.Perform database queries or updates through the database operation interface in programming languages, and obtain the required data.
4.The programming language processes the data retrieved from the database and generates HTML content as needed.
5.The server sends the generated HTML content back to the client as an HTTP response.
6.The client receives the response and renders the HTML to the user on the browser.

Design Process
A simple calculator should contain numbers, operators and function keys.

Numbers: integers from 0 to 9
Operators: the basic four operations addition, subtraction, multiplication and division
Function: empty, backspace, parentheses, equal functions. On the basis of realizing these functions, trigonometric function and inverse trigonometric function as well as square and square root operations are performed on the results.

Implementation Process

  1. The interface only needs to fix the width and height of the calculator panel and the width and height of the button. Then select text styles and page colors to beautify it.
  2. If a number (0,1,2,3,4,5,6,7,8,9) and “(”, “)”, “.” is clicked, it will be displayed in the input text box above (hereinafter referred to as the output box) and append (+=) in a string content.
  3. If an operator button (+, -, *, /, ^, √, sin, cos, tan, arcsine, arccosine, arctan) is clicked, it will perform related operations and output results.
  4. If “C” is clicked, the string content is cleared, and the output box is also cleared.
    If “←” is clicked, clear the content string with the last character and set the output box to the value of content.
  5. If you click “=”, the result of the calculation is displayed in the output box and the content is cleared.
  6. Using the eval () function, this function can execute the js statement in it, and return the result if it can be executed, or directly return the original statement if it cannot be executed.

Underlying principle

  • The underlying principle is that the server-side programming language connects to the MySQL database through appropriate database drivers (such as MySQL, PDO, etc.) and uses SQL query language to interact with the database. SQL query language is used to perform queries, inserts, updates, and deletions to retrieve, modify, or delete data from a database.

  • The database operation interface in programming languages provides methods and functions for interacting with MySQL databases, such as connecting to a database, executing SQL query statements, and obtaining query results. Through these interfaces, operations such as querying specific data, inserting new data, updating existing data, or deleting data can be performed.

  • After retrieving the required data from the database, the programming language processes the data and populates it into HTML templates or dynamically generates HTML content. In this way, the generated HTML content will contain the data retrieved from the database for display on the browser.

  • The entire process involves the collaboration of server-side programming languages, database drivers, and SQL query languages, thereby achieving interaction between MySQL databases and HTML pages.

Flow chart
在这里插入图片描述

6. Project code
HTML+CSS+JS

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>科学计算器</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: #f0f0f0;
            font-family: sans-serif;
            overflow-y: scroll;
        }

        ::-webkit-scrollbar {
            display: none;
        }

        .calculator {
            width: 380px;
            display: flex;
            flex-direction: column;
            padding: 20px;
            background-color: #3a4452;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            padding-right: 0;
        }

        .screen {
            overflow: hidden;
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            justify-content: center;
            height: 60px;
            margin-bottom: 10px;
            padding-right: 10px;
            /* border: 1px solid #888; */
            border-radius: 5px;
            font-size: 24px;
            letter-spacing: 2px;
            line-height: 1.2;
            overflow-x: scroll;
            white-space: nowrap;
            color: #fff;
        }

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

        button {
            height: 60px;
            width: 60px;
            border: none;
            border-radius: 8px;
            background-color: #3a4452;
            cursor: pointer;
            font-size: 18px;
            transition: all 0.1s ease-in-out;
            box-shadow: -10px -8px 4px rgba(216, 215, 215, 0.1);
            border: 1px solid rgba(197, 197, 197, 0.1);
            color: #fff;
            text-align: center;
            /* 添加阴影效果 */
        }

        button:hover {
            opacity: 0.8;
        }

        .number {
            /* background-color: #f7f7f7; */
            color: #444;
        }

        .operator {
            /* background-color: #ff9900; */
            color: #fff;
        }

        .clear {
            /* grid-column: 1/ span 1; */
            /* background-color: #f00; */
            color: #fff;
        }

        .clear2 {
            grid-column: span 4;
            /* background-color: #f00; */
            color: #fff;
        }

        .equal {
            /* grid-column: 2 / span 2; */
            /* background-color: #00f; */
            color: #fff;
        }

        .all-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
        }

        .all-row .clear2 {
            grid-column: 1 / -1;
        }

        .all-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            grid-gap: 10px;
        }

        .all-row .clear2 {
            grid-column: 1 / -1;
            /* 跨越所有列 */
            width: 400%;
        }
    </style>
</head>

<body>
    <div class="calculator">
        <div class="screen" id="screen"></div>
        <div class="buttons">
            <button class="clear" onclick="clearScreen()" style="color: #33ffd8;">Clear</button>
            <button onclick="ans()" style="color: #33ffd8;">ans</button>
            <button onclick="addSymbol('(')" style="color: #33ffd8;">(</button>
            <button onclick="addSymbol(')')" style="color: #33ffd8;">)</button>
            <button onclick="addSymbol('%')" style="color: #33ffd8;">%</button>
            <button onclick="addNumber(7)">7</button>
            <button onclick="addNumber(8)">8</button>
            <button onclick="addNumber(9)">9</button>
            <button class="operator" onclick="addSymbol('/')" style="color: #33ffd8;">/</button>
            <button onclick="addNumber(4)">4</button>
            <button onclick="addNumber(5)">5</button>
            <button onclick="addNumber(6)">6</button>
            <button class="operator" onclick="addSymbol('*')" style="color: #33ffd8;">*</button>
            <button onclick="addNumber(1)">1</button>
            <button onclick="addNumber(2)">2</button>
            <button onclick="addNumber(3)">3</button>
            <button class="operator" onclick="addSymbol('-')" style="color: #33ffd8;">-</button>
            <button onclick="addSymbol('log(')" style="color: #33ffd8;">log</button>
            <button onclick="addNumber(0)">0</button>
            <button onclick="addSymbol('.')" style="color: #33ffd8;">.</button>
            <button class="operator" onclick="addSymbol('+')" style="color: #33ffd8;">+</button>
            <button onclick="addSymbol('tan(')" style="color: #33ffd8;">tan</button>
            <button onclick="addSymbol('sin(')" style="color: #33ffd8;">sin</button>
            <button onclick="addSymbol('cos(')" style="color: #33ffd8;">cos</button>
            <button onclick="addSymbol('sqrt(')" style="color: #33ffd8;"></button>
            <button onclick="addSymbol('e')" style="color: #33ffd8;">e</button>
            <button onclick="addSymbol('^')" style="color: #33ffd8;">x^y</button>
            <button class="equal" onclick="calculate()" style="color: #33ffd8;">=</button>
            <!-- <button class="clear2" οnclick="clearScreen()" style="color: #33ffd8;">all</button> -->
            <div class="all-row">
                <button class="clear2" onclick="allShow()" style="color: #33ffd8;">All</button>
            </div>
        </div>
    </div>

    <script>
        let numType = 0
            // 一开始,获取id
            ; (function getId() {
                fetch('http://8.219.120.3:7788/caculate/get', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(0)
                }).then(response => response.json())
                    .then(data => {
                        numType = data.id
                        console.log(numType, 'numType')
                    })
                    .catch(error => console.error(error))
            })()

        console.log(numType, 'numType2')
        // 获取屏幕元素
        let screen = document.getElementById('screen')

        // 清空屏幕
        function clearScreen() {
            screen.innerHTML = ''
            numType++
        }

        // 添加数字
        function addNumber(num) {
            screen.innerHTML += num
        }

        // 添加符号
        var lastSymbolAdded
        function addSymbol(symbol) {
            if (symbol === '^' || symbol === '**') {
                symbol = '**'
            } else if (symbol === 'sin(' || symbol === 'cos(' || symbol === 'tan(' || symbol === 'log(' || symbol === 'sqrt(') {
                // 添加函数或根号时,记录最后添加的符号
                lastSymbolAdded = symbol

                screen.innerHTML += symbol
                return
            } else if (lastSymbolAdded === 'sqrt(') {
                // 在sqrt(后直接添加数字或变量名时,补全表达式
                if (!isNaN(parseFloat(symbol))) {
                    screen.innerHTML = screen.innerHTML.slice(0, -1) // 删除右括号
                    // screen.innerHTML += symbol + ')'
                } else {
                    // screen.innerHTML = screen.innerHTML.slice(0, -1) // 删除右括号
                    // screen.innerHTML += ')' + symbol
                }
                lastSymbolAdded = undefined
                return
            }
            screen.innerHTML += symbol
            lastSymbolAdded = undefined
        }

        // 计算结果
        function calculate() {
            try {
                let expression = screen.innerHTML
                let numComputed = screen.innerHTML
                console.log(expression, 'expression')
                // 将 sin 替换为 Math.sin,并将角度转换为弧度
                expression = expression.replace(/sin\((\d+)\)/g, function (match, angle) {
                    let radians = parseFloat(angle) * (Math.PI / 180)
                    return Math.sin(radians)
                })
                // 将 cos 替换为 Math.cos,并将角度转换为弧度
                expression = expression.replace(/cos\((\d+)\)/g, function (match, angle) {
                    let radians = parseFloat(angle) * (Math.PI / 180)
                    return Math.cos(radians)
                })
                // 将 tan 替换为 Math.tan,并将角度转换为弧度
                expression = expression.replace(/tan\((\d+)\)/g, function (match, angle) {
                    let radians = parseFloat(angle) * (Math.PI / 180)
                    return Math.tan(radians)
                })
                // 将 log 替换为 Math.log()
                expression = expression.replace(/log\((\d+)\)/g, function (match, number) {
                    return Math.log(parseFloat(number))
                })

                expression = expression.replace(/sqrt\((\d+)\)/g, function (match, number) {
                    return Math.sqrt(number)
                })

                let result = eval(expression)
                screen.innerHTML = result.toLocaleString()
                let datas = `${expression}=${result.toLocaleString()}`

                fetch('http://8.219.120.3:7788/caculate/save', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(datas)
                }).then(response => response.json())
                    .then(data => {
                        numType++
                        // 获取浏览器list
                        let list = window.localStorage.getItem("list") ? JSON.parse(window.localStorage.getItem("list")) : []

                        if (list.length > 10) {
                            list.shift() // 去掉第一位
                        }

                        list.push(`${numComputed}=${result.toLocaleString()}`) // 往数组末尾添加元素

                        window.localStorage.setItem("list", JSON.stringify(list)) // 将数组存入浏览器
                    })
                    .catch(error => console.error(error))
            } catch (error) {
                alert('输入表达式有误,请检查!')
            }
        }

        function ans() {
            if (numType) {
                fetch('http://8.219.120.3:7788/caculate/get', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(numType)
                }).then(response => response.json())
                    .then(data => {
                        const regExp = /=(\d+)/
                        const matchArr = data.r.match(regExp)
                        const num = matchArr && matchArr[1]
                        console.log(num) // 输出 785
                        numType--
                    })
                    .catch(error => console.error(error))
            } else {
                alert("没有更多数据....")
            }
        }

        function allShow() {
            let list = JSON.parse(window.localStorage.getItem("list"))
            screen.innerHTML = list.join(',')
        }
    </script>
</body>

</html>

The specific code for MySQL can be found in github

``

7. Summary

In this task, I upgraded my calculator comprehensively, not only adding more and more complex computing functions, but also utilizing a combination of front-end and back-end technologies to enable the calculator to store historical records and support queries.
After training in the previous task, I can feel that writing the front-end is easier, so writing more complex calculator functions did not cause me much trouble. On the contrary, I also learned more relevant knowledge points through writing. The writing of front-end code is also more effortless.

But when writing database knowledge, I encountered difficulties. I have never been exposed to relevant knowledge before, and I rarely even heard of it. So when I spend much more time on the first task than on the second task. Since I first learned about homework content, I have been searching online for relevant backend information and understanding the basic content of the database. From processing the backend separately at the beginning to being able to achieve front-end and back-end interaction, each step for me is a process of receiving new knowledge.

But when writing database knowledge, I encountered difficulties. I have never been exposed to relevant knowledge before, and I rarely even heard of it. So when I spend much more time on the first task than on the second task. Since I first learned about homework content, I have been searching online for relevant backend information and understanding the basic content of the database. From processing the backend separately at the beginning to being able to achieve front-end and back-end interaction, each step for me is a process of receiving new knowledge.
At the same time, I also understand that it is unlikely to master backend technology proficiently in such a short period of time. After this assignment, I still need to continuously improve my abilities and calculator skills

At the same time, I also understand that it is unlikely to master backend technology proficiently in such a short period of time. After this assignment, I still need to continuously improve my abilities and calculator skills

wanqu

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值