WEB/JS

[JS] 6-2. 과제 - 연산자

개발자 만두 2021. 9. 20. 16:58
728x90
반응형

✅오늘의 과제

➰console.log()를 이용하여 사칙연산 출력하기

 

➰코드

day6.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>day6</title>
    <style>
        body {
            margin-top: 30vh;
        }
        div {
            text-align: center;
        }
        button {
            background-color: slategray;
            border-radius: 20px;
        }
        .operand {
            padding: 30px;
            font-size: 30px;
        }
        .operator {
            padding: 50px;
            font-size: 50px;
        }
        .operation {
            padding: 10px 20px;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <div>
        <button type="button" id="xy" class="operand" onclick="operand()">x, y</button>
    </div><br>
    <div>
        <button type="button" id="+" class="operator" onclick="operator(0)">+</button>
        <button type="button" id="-" class="operator" onclick="operator(1)">-</button>
        <button type="button" id="*" class="operator" onclick="operator(2)">*</button>
        <button type="button" id="/" class="operator" onclick="operator(3)">/</button>
        <button type="button" id="%" class="operator" onclick="operator(4)">%</button>
    </div><br>
    <div>
        <button type="button" class="operation" onclick="answer()">계산식 콘솔창에 출력하기</button>
    </div>
    <script src="day6.js"></script>
</body>
</html>

 

 

day6.js

let input;
let input_x;
let input_y;
let clickedOperator;
let dap;

function operand() {
    input = prompt().split(',');
    input_x = Number(input[0]);
    input_y = Number(input[1]);
}

function operator(n) {
    if (n === 0) {
        clickedOperator = '+';
        dap = input_x + input_y;
    } else if (n === 1) {
        clickedOperator = '-';
        dap = input_x - input_y;
    } else if (n === 2) {
        clickedOperator = '*';
        dap = input_x * input_y;
    } else if (n === 3) {
        clickedOperator = '/';
        dap = parseInt(input_x / input_y);
    } else {
        clickedOperator = '%';
        dap = input_x % input_y;
    }
}

function answer() {
    console.log('x', clickedOperator, 'y', '=', dap);
}

 

 

코드 설명

x, y버튼을 클릭하면 operand() 함수가 실행되고 두 숫자를 prompt로 입력받아 순서대로 변수 input_x, input_y에 대입한다. 그다음 연산자 버튼을 누르면 operator(n) 함수가 실행되고 n의 값에 따라 어떤 연산자 버튼이 눌렸는지 알아낸다. 변수 clickedOperator에 해당 연산자를 문자열로 저장하고 위의 두 변수로 연산을 실행한 결괏값을 변수 dap에 저장한다. 계산식 콘솔창에 출력하기 버튼을 누르면 answer() 함수가 실행되고 저장해두었던 변수 clickedOperator와 변수 dap의 값을 포함한 계산식을 콘솔에 출력한다.

 

➰코드실행화면(https://jsday6.netlify.app)

 

 

➰GitHub

https://github.com/minseon6371/javascript-study/tree/main/day6

 

GitHub - minseon6371/javascript-study

Contribute to minseon6371/javascript-study development by creating an account on GitHub.

github.com

 

728x90
반응형