Simple Calculator Based on JavaScript

I. Introduction

The blog is used to record the production process for Software Engineering Practice First Assignment of EE302

The Link Your Classhttps://bbs.csdn.net/forums/ssynkqtd-04
The Link of Requirement of This Assignmenthttps://bbs.csdn.net/topics/617332156
The Aim of This AssignmentVisual Calculator
MU STU ID and FZU STU IDMU ID 21126640 & FZU ID 832101104

Link to finished project code: https://github.com/SuJob1/Calculator/blob/main/

II. Project

This calculator based on CSS, HTML, JavaScript design can implement simple addition, subtraction, multiplication and division as well as trigonometric and power functions

1.PSP form

Personal Software Process StagesEstimated Time(minutes)Actual Time(minutes)
Planning4045
• Estimate4045
Development312370
• Analysis3035
• Design Spec1210
• Design Review1520
• Coding Standard2015
• Design6075
• Coding120150
• Code Review3035
• Test2530
Reporting120130
• Test Report6065
• Size Measurement3025
• Postmortem & Process Improvement Plan3040
Sum472545

2 .Description of problem-solving ideas

How I design this calculator

  • Function: At first, I need to create the calculator which can achieve some basic functions like addition, subtraction, multiplication and division. Then I need to add some extra advanced functions like power functions and trigonometric functions.
  • Language: Then, I decide to use JavaScript with CSS and HTML which can be nice tools to make the visual calculator in the Web.

How I find the information

  • Website: When I have determined the function, I want to implement and the method of use, I find some relative information on Bilibili, Csdn, Zhihu, GitHub and other websites.

3. Design and implementation process

3.1 Design:

3.1.1 User Interface:
  • Centered Layout: The calculator is designed with a circular, centered layout to give it a distinct look.

  • Stylized Buttons and Display: Buttons are stylized with specific colors, shadow effects, and a rounded design. The display is right-aligned for better readability of numbers.

  • Clear Hierarchy: Titles, buttons, and display areas are well organized to guide users intuitively through the interface.

3.1.2 Functionality:
  • Basic Arithmetic: Supports addition+, subtraction-, multiplication*, and division/.

  • Advanced Operations: Includes trigonometric functions such as sin, cos, tan, and power operation using ^.

  • Error Handling: The calculator is designed to handle errors and display an error message when faced with an invalid operation.

  • Usability Features: Clear all functionality and delete one character functionality for ease of use.

3.2 Implementation:

3.2.1 HTML Structure:
  • Form Structure: The calculator layout is wrapped inside a form, allowing grouping of input elements.

  • Input Elements: Each button is an input element of type button with specific values and onclick functions to capture user actions.

3.2.2 CSS Styling:
  • Reset Defaults: Default margins, paddings, borders, and fonts are reset to ensure consistent appearance.

  • Custom Styles: Each button, display, and the overall calculator have custom styles defined using classes like .btn, .number, .operator, and .other.

3.2.3 JavaScript Logic:
  • Event Listeners: The “clear” button uses an event listener to clear the display when clicked.

  • Value Appender: A get function appends the value of clicked buttons to the display.

  • Calculator Logic: The calculates function evaluates the mathematical expression entered by the user.

    • Trigonometry Support: Before evaluation, trigonometric functions are pre-processed using the processTrigonometry function.

    • Power Operation: The expression is also processed to handle power operations using ^.

  • Error Handling: Try-catch blocks handle any calculation errors, ensuring the user is informed of invalid operations.

  • Helper Functions: Functions like toRadians and roundNumber assist in calculations and conversions.

3.2.4 Flow Chart:

Flow Chart

4. Code description

  • CSS: The CSS code is for styling. It gives the calculator a clean, modern look. It defines styles such as colors, button sizes, and display properties.
 /* Reset */
 * {
    border: none; /* Clear default borders */
    font-family: 'Open Sans', Arial; /* Set font */
    margin: 0; /* Clear default margins */
    padding: 0; /* Clear default paddings */
}

/* Center the calculator */
.center {
    background-color: #fff;
    border-radius: 100%; /* Circular shape */
    height: 600px;
    margin: auto; /* Center horizontally */
    width: 600px;
}

/* Header styling */
h1 {
    color: #495678;
    font-size: 40px;
    margin-top: 20px;
    padding-top: 15px;
    display: block;
    text-align: center;
    text-decoration: none;
}

/* Form styling */
form {
    background-color: #495678;
    box-shadow: 4px 4px #3d4a65;
    margin: 20px auto;
    padding: 40px 0 30px 40px;
    width: 315px;
}

/* Button styling */
.btn {
    cursor: pointer; /* Hand pointer */
    font-size: 20px;
    height: 45px;
    margin: 5px 0 7px 10px;
    outline: none; /* Clear default outline */
    width: 45px;
}

.btn:first-child {
    margin: 5px 0 5px 10px;
}

/* Styles for the display, buttons, and form */
.btn, #display, form {
    border-radius: 25px;
}

/* Display styling */
#display {
    background-color: #98d1dc;
    box-shadow: inset 6px 6px 0px #3facc0;
    color: #dededc;
    font-size: 20px;
    height: 47px;
    margin-left: 10px;
    padding-right: 10px;
    text-align: right;
    width: 265px;
}

/* Button styling based on their type */
.number {
    background-color: #72778b;
    box-shadow: 0 5px #5f6680;
    color: #dededc;
}

.number:active {
    box-shadow: 0 2px #5f6680;
    transform: translateY(2px);
}

.operator {
    background-color: #dededc;
    box-shadow: 0 5px #bebebe;
    color: #72778b; 
}

.operator:active {
    box-shadow: 0 2px #bebebe;
    transform: translateY(2px);
}
.zero {          
    width: 105px;
    background-color: #72778b;
    box-shadow: 0 5px #5f6680;
    color: #dededc;
}
.zero:active {
    box-shadow: 0 2px #5f6680;
    transform: translateY(2px);
}
.other {
    background-color: #e3844c;
    box-shadow: 0 5px #e76a3d;
    color: #dededc;
}

.other:active {
    box-shadow: 0 2px #e76a3d;
    transform: translateY(2px);
}
  • HTML: The HTML code provides the structure for the calculator, laying out buttons for digits 0-9, common mathematical operations (addition, subtraction, etc.), and trigonometric functions like sin, cos, and tan.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
</head>
<body>
    <div class="center">
        <h1>Calculator</h1>
        <form name="calculator">
            <input type="text" id="display">
            <br>
            <input type="button" id="clear" class="btn other" value="C">
            <input type="button" class="btn operator" value="(" onclick="get(this.value);">
            <input type="button" class="btn operator" value=")" onclick="get(this.value);">
            <input type="button" class="btn operator" value="^" onclick="get(this.value);">
            <input type="button" class="btn operator" value="+" onclick="get(this.value);">
            <br>
			<input type="button" class="btn number" value="7" onclick="get(this.value);">
			<input type="button" class="btn number" value="8" onclick="get(this.value);">
			<input type="button" class="btn number" value="9" onclick="get(this.value);">
			<input type="button" class="btn operator" value="sin" onclick="get(this.value);">
			<input type="button" class="btn operator" value="-" onclick="get(this.value);">
			
			<br>
			<input type="button" class="btn number" value="4" onclick="get(this.value);">
			<input type="button" class="btn number" value="5" onclick="get(this.value);">
			<input type="button" class="btn number" value="6" onclick="get(this.value);">
			<input type="button" class="btn operator" value="cos" onclick="get(this.value);">
			<input type="button" class="btn operator" value="*" onclick="get(this.value);">
			
			<br>
			<input type="button" class="btn number" value="1" onclick="get(this.value);">
			<input type="button" class="btn number" value="2" onclick="get(this.value);">
			<input type="button" class="btn number" value="3" onclick="get(this.value);">
			<input type="button" class="btn operator" value="tan" onclick="get(this.value);">
			<input type="button" class="btn operator" value="/" onclick="get(this.value);">		

			<br>
			<input type="button" class="btn zero" value="0" onclick="get(this.value);">
			<input type="button" class="btn operator" value="." onclick="get(this.value);">	
            <input type="button" class="btn other" value="Del" onclick="deleteLastCharacter();">		
            <input type="button" class="btn other" value="=" onclick="calculates();">
        </form>
    </div>
</body>
</html>

  • JavaScript:
    • Interactivity: The JavaScript code makes the calculator interactive. When a button is pressed, its value gets added to the display.
    • Trigonometric Functions: Before a calculation occurs, any trigonometric functions (like sin, cos, tan) are detected and processed.
    • Exponential Function: This detects the use of the ‘^’ symbol to compute power operations.
    • Result Calculation: Once all special functions are processed, the eval() function calculates the result. Any errors in calculation will display the message “Error”.
        // Clear the display
        document.getElementById("clear").addEventListener("click", function() {
            document.getElementById("display").value = "";
        });

        // Append value to the display
        function get(value) {
            document.getElementById("display").value += value;
        }

        // Evaluate the result
        function calculates() {
            var displayValue = document.getElementById("display").value;
            displayValue = processTrigonometry(displayValue);
            try {
                 var result = eval(displayValue);
                 document.getElementById("display").value = result;
                } catch (error) {
                    document.getElementById("display").value = "Error";
                 }
            }
        // Process trigonometric functions
        function processTrigonometry(value) {
            value = value.replace(/(\d*)sin(\d+)/g, function(match, coefficient, angle) {
            coefficient = coefficient || '1';  // Default coefficient to 1 if it's absent
            return roundNumber(coefficient * Math.sin(toRadians(Number(angle))), 5);
            });

            value = value.replace(/(\d*)cos(\d+)/g, function(match, coefficient, angle) {
            coefficient = coefficient || '1';  // Default coefficient to 1 if it's absent
            return roundNumber(coefficient * Math.cos(toRadians(Number(angle))), 5);
            });

            value = value.replace(/(\d*)tan(\d+)/g, function(match, coefficient, angle) {
            coefficient = coefficient || '1';  // Default coefficient to 1 if it's absent
            return roundNumber(coefficient * Math.tan(toRadians(Number(angle))), 5);
            });

            value = value.replace(/(\d+)\^(\d+)/g, function(match, base, exponent) {
            return Math.pow(Number(base), Number(exponent));
            });
        return value;
}


        // Round number to a certain decimal place
        function roundNumber(num, scale) {
            if(!("" + num).includes("e")) {
                return +(Math.round(num + "e+" + scale) + "e-" + scale);
            } else {
                var arr = ("" + num).split("e");
                var sig = ""
                if(+arr[1] + scale > 0) {
                    sig = "+";
                }
                return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
            }
        }

        // Convert degrees to radians
        function toRadians(degrees) {
            return degrees * (Math.PI / 180);
        }
        function deleteLastCharacter() {
            var display = document.getElementById("display");
            display.value = display.value.slice(0, -1);
        }

5. Displaying result

在这里插入图片描述

6. Summary

This work let me know how to do the whole process of making a new project from planning, analysis, code writing, code modification and test results, and what to pay attention to. In addition, my familiarity with GitHub and related programming codes has been greatly improved, which is of great help for me to learn the courseoftware engineer.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值