2.More advanced front and back end calculators

832101323高畅 2023-10-22 14:40:42

catalogue

1.introduction

2.requirements(assignment table)

3.psp form

4.display

5.front,back code

6.flow graph

7.summary

 

 

1.introduction

We have employed Visual Studio Code to facilitate the operations of addition, subtraction, multiplication, division, finding residuals, trigonometric functions, and logarithmic functions. Additionally, we have enabled the "ans" button to retrieve previous calculation records. HTML alone, as a language solely designed for web page structure, lacks the capability to handle computational logic and data storage, thus unable to achieve the aforementioned functions. Therefore, JavaScript is utilized to handle front-end logic processing and back-end data storage tasks.

2.requirements(assignment table)

The Link Your Classbluesspirit/codingworks (github.com)
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617378696
The Aim of This AssignmentLearn the basic process of backend data interaction
MU STU ID and FZU STU ID21124574  832101323

3.psp form

PSPEstimated time Actual time
 Estimate1510
Development250300
 Analysis1515
Design Spec1515
Design Review3030
Coding Standard  
Design5055
Coding180230
CodeReview1010
Test3540
Reporting2030
Test Report  
Size Measurement1515
Postmortem & Process Improvement Plan2020
planning1515
sum670785

4.display

basic function:

 

history:

 

advanced function:

 

 

5.front,back code

Front End:

The front-end interface, crafted using HTML, showcases an input section, a results display zone, a history area, and several control buttons. The reconstruction functionality enables the history area to receive and showcase data from the back end. In simpler terms, it forwards input data to the back-end database for processing.

Back End:

The back end is a Node.js server, built on Express, offering two key APIs: one for evaluating expressions and another for retrieving history. The eval function examines the result (saved in the history list, allowing for minor errors) for any errors, displaying the evaluated data on the cmd command line. Eventually, we pass the results and history back to the front end and database. Additionally, we've incorporated the cors function to permit the server to receive data from domains that differ.

front end design:

<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f5f5f5;
margin: 0;
font-family: Arial, sans-serif;
}
#calculator {
border: 1px solid #ddd;
border-radius: 5px;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
#display {
width: 100%;
height: 50px;
margin-bottom: 10px;
text-align: right;
padding-right: 5px;
font-size: 1.5em;
}
.button {
width: 50px;
height: 50px;
margin: 5px;
}
#result {
margin-top: 10px;
font-weight: bold;
}
#history {
margin-top: 20px;
list-style: none;
padding: 0;
}
</style>
</head>
<body>
<div id="calculator">
<input id="display" type="text" readonly><br>
<p id="result"></p><br>
<button class="button" onclick="append('1')">1</button>
<button class="button" onclick="append('2')">2</button>
<button class="button" onclick="append('3')">3</button>
<button class="button" onclick="append('+')">+</button>
<button class="button" onclick="append('-')">-</button><br>
<button class="button" onclick="append('4')">4</button>
<button class="button" onclick="append('5')">5</button>
<button class="button" onclick="append('6')">6</button>
<button class="button" onclick="append('*')">*</button>
<button class="button" onclick="append('/')">/</button><br>
<button class="button" onclick="append('7')">7</button>
<button class="button" onclick="append('8')">8</button>
<button class="button" onclick="append('9')">9</button>
<button class="button" onclick="append('%')">%</button>
<button class="button" onclick="append('^')">^</button><br>
<button class="button" onclick="append('0')">0</button>
<button class="button" onclick="append('(')">(</button>
<button class="button" onclick="append(')')">)</button>
<button class="button" onclick="append('log(')">log</button>
<button class="button" onclick="append('ln(')">ln</button><br>
<button class="button" onclick="append('sin(')">sin</button>
<button class="button" onclick="append('cos(')">cos</button>
<button class="button" onclick="append('tan(')">tan</button>
<button class="button" onclick="append('sqrt(')">sqrt</button>
<button class="button" onclick="append('e')">e</button><br>
<button class="button" onclick="clearDisplay()">C</button>
<button class="button" onclick="deleteLast()">Del</button>
<button class="button" onclick="calculate()">=</button>
<button id="history-button" class="button">Ans</button>
<button class="button" onclick="append('Π')">Π</button><br>
 
<ul id="history"></ul>
</div>
    <script src="Calculaor2.js"></script>
 
</body>
</html>

 

let display = document.getElementById('display');
let result = document.getElementById('result');
let isClicked = false;
 
function append(str) {
    display.value += str;
}
 
function clearDisplay() {
    display.value = '';
    result.textContent = '';
}
 
function deleteLast() {
    display.value = display.value.slice(0, -1);
}
 
// Prepare the expression for calculation
function prepareExpression(expression) {
    expression = expression.replace(/tanh|cos|log|sin|exp|sqrt|tan|ln|e|Π/g, match => {
        switch (match) {
            case 'tanh':
            case 'cos':
            case 'log':
            case 'sin':
            case 'exp':
            case 'sqrt':
            case 'tan':
                return 'Math.' + match;
            case 'ln':
                return 'Math.log';
            case 'e':
                return 'Math.E';
            case 'Π':
                return 'Math.PI';
            default:
                return match;
        }
    });
    return expression.replace(/\^/g, '**');
}
 
async function calculate() {
    let preparedExpression = prepareExpression(display.value);
    let response = await fetch('http://localhost:3000/calculate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({expression: preparedExpression}),
    });
    let data = await response.json();
    if (data.error) {
        result.textContent = 'Error';
    } else {
        result.textContent = data.result;
        display.value = '';
        updateHistory();
    }
}
 
async function updateHistory() {
    let response = await fetch('http://localhost:3000/history');
    let data = await response.json();
    displayHistory(data);
}
 
function displayHistory(historyData) {
    let historyElement = document.getElementById('history');
    if(isClicked) {
        historyElement.style.display = 'block';
        historyElement.innerHTML = '';
        for (let i = historyData.length - 1; i >= 0; i--) {
            let li = document.createElement('li');
            li.textContent = historyData[i].expression + ' = ' + historyData[i].result;
            li.onclick = function() {
                display.value = historyData[i].expression;
            };
            historyElement.appendChild(li);
        }
    } else {
        historyElement.style.display = 'none';
    }
}
 
document.getElementById('history-button').onclick = function() {
    isClicked = !isClicked;
    updateHistory();
}

back-end design

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
 
app.use(cors()); 
 
// Use JSON body parser middleware
app.use(bodyParser.json());
 
// Initialize SQLite database
let db = new sqlite3.Database('database.db', (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('Connected to the SQLite database.');
});
 
// Create history table
db.run('CREATE TABLE IF NOT EXISTS history(expression text, result text)', (err) => {
  if (err) {
    return console.error(err.message);
  }
  console.log('History table created.');
});
 
app.post('/calculate', (req, res) => {
  let expression = req.body.expression;
  let result;
  try {
    result = eval(expression);
    // Insert the expression and result to the history table
    db.run(`INSERT INTO history(expression, result) VALUES(?, ?)`, [expression, result], function(err) {
      if (err) {
        return console.log(err.message);
      }
      console.log(`A row has been inserted with rowid ${this.lastID}`);
      
      // Check the number of rows in the history table and delete the oldest if there are more than 10
      db.run(`DELETE FROM history WHERE rowid NOT IN (SELECT rowid FROM history ORDER BY rowid DESC LIMIT 10)`);
    });
    res.json({ result: result });
  } catch (e) {
    res.json({ error: 'Invalid expression' });
  }
});
 
// Endpoint to get calculation history
app.get('/history', (req, res) => {
  db.all('SELECT * FROM history ORDER BY rowid DESC', [], (err, rows) => {
    if (err) {
      throw err;
    }
    console.log(rows); // Print history data
    res.json(rows);
  });
});
 
// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

 

 

6.flow graph

 

7.summary 

Throughout this project, I gained hands-on experience with the front-end and back-end separation development model, a widely-used approach among modern web application engineers. The front-end focuses on user interface and interaction, while the back-end handles data processing and storage, with both communicating via HTTP api. This model enables independent development and testing for both front-end and back-end, ultimately boosting development efficiency.

I utilized HTML and JavaScript for front-end coding, Node.js and Express for the back-end, and SQLite for the database. Thankfully, extensive documentation and community support were available to assist with any challenges encountered during my implementation.

Some hurdles I faced included handling user-inputted expressions, setting limits on history quantity, and returning expressions to the input box upon user's history click. However, through documentation exploration and experimentation, I successfully resolved these issues, further solidifying my understanding of these technologies.

Anticipations:

While this calculator performs adequately, there are numerous areas ripe for enhancement, making it far from a "super" calculator. Presently, it only supports basic mathematical functions, but I envision expanding its capabilities to include a wider range of functions and constants. I also plan to revamp the history display, allowing users to view entries in chronological order and even search or filter through them.

My ultimate goal is to transform this calculator into a comprehensive web application or a user-friendly mobile app, complete with registration and login features. This will enable users to save and share their history with others. To achieve these functionalities, I plan to delve deeper into technologies like user authentication, database optimization, and front-end frameworks.

I am eager to continue refining my skills in future learning and development endeavors, acquire more knowledge, implement additional features, and ultimately, deliver an exceptional user experience.

 

 

 

 

 

...全文
51 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
内容概要:本文系统研究了基于豪猪优化算法(CPO)的多无人机协同集群在三维空间中的避障路径规划问题,聚焦于实现以最低成本为目标的航迹优化,综合考虑路径长度、飞行高度、威胁规避及转弯角度等多个关键因素。通过构建精细化的三维环境模型与多无人机协同机制,采用Matlab平台实现CPO算法的仿真与验证,充分展示了该算法在复杂动态障碍环境下的高效搜索能力与全局优化性能。研究不仅涵盖了路径规划的数学建模与目标函数设计,还深入探讨了算法的收敛特性与鲁棒性,为智能群体系统在实际场景中的应用提供了理论依据与技术支撑。; 适合人群:具备一定编程基础和优化算法背景,从事无人机系统控制、智能路径规划、群体协同、人工智能与自动化等相关领域的科研人员、高校研究生及工程技术人员。; 使用场景及目标:①应用于多无人机协同执行侦察、灾害监测、应急救援、区域巡检等复杂任务中的自主路径规划;②为智能优化算法在三维动态环境下的路径决策问题提供可复现的技术范例;③支持研究人员对CPO算法与其他主流群智能算法(如PSO、GWO、WOA等)进行性能对比与改进研究,推动路径规划技术的发展。; 阅读建议:建议结合提供的Matlab代码进行实践操作,重点理解目标函数的多维度建模方式与CPO算法的迭代优化流程,可通过调整环境参数与约束条件进行仿真实验,对比不同算法在相同场景下的路径质量与收敛速度,从而深入掌握其优势与适用边界。
内容概要:本文围绕电动汽车参与电力系统运行备用的能力评估展开深入研究,利用Matlab代码实现对电动汽车集群提供运行备用服务的建模与仿真分析。研究重点在于量化电动汽车作为分布式灵活资源参与电网辅助服务的潜力,通过构建精细化的数学模型,分析其可调功率容量、响应速度、时空分布特性及聚合能力,并采用多面体聚合、内近似模型与闵可夫斯基和等先进方法精确刻画其可调度能力边界。研究进一步结合大规模电动汽车接入场景,探讨其在多时间尺度调度框架下参与调峰、调频等辅助服务的优化策略,评估其对提升高比例可再生能源电网灵活性与稳定性的贡献,最终通过仿真验证所提模型与方法的有效性与实用性。; 适合人群:具备电力系统分析、智能电网、新能源汽车或优化调度等相关专业背景,熟悉Matlab/Simulink仿真工具,从事科研、工程应用的高校研究生、科研人员及电力行业工程师。; 使用场景及目标:①精确评估大规模电动汽车集群在不同约束条件下可提供的运行备用容量;②研究电动汽车在日前、日内及实时调度中的动态响应能力与优化调度策略;③为高渗透率新能源电力系统提供基于移动储能的灵活性资源解决方案,支撑电网安全经济运行。; 阅读建议:建议结合Matlab代码与技术文档同步学习,重点关注多面体聚合建模、能力边界计算及优化调度算法的设计与实现,可进一步拓展至V2G(车辆到电网)、需求响应等互动场景进行二次开发与应用验证。

176

社区成员

发帖
与我相关
我的任务
社区描述
梅努斯软件工程
软件工程 高校 福建省·福州市
社区管理员
  • LinQF39
  • Jcandc
  • chjinhuu
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧