반응형

[ 계산기 레이아웃 ]


[ HTML 코드 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Calculator</title>
</head>
<body>
    <table width=500 align=center>
        <th colspan="5">계산기</th>
        <tr>
            <td colspan=5 align=center><input type="text" id="showText"
                style="width: 350pt; height: 20pt"></td>
        </tr>
        
        <tr>
            <td colspan=3 align=center><input type="button" id="clearBtn"
                onclick=clearAll() value="Clear" style="width: 130pt; height: 30pt"></td>
            <td colspan=2 align=left><input type="button" id="equal"
                onclick=getResult() value="=" style="width: 130pt; height: 30pt"></td>
        </tr>
        
        <tr>
            <td align=center><input type=button id=1 value=1
                onclick=selectedBtn(1) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=2 value=2
                onclick=selectedBtn(2) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=3 value=3
                onclick=selectedBtn(3) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=plus value=+
                onclick=selectedOp("+") style="width: 40pt; height: 30pt"></td>
            <td align=left><input type=button id=square value=x^y
                onclick=selectedOp("^") style="width: 40pt; height: 30pt"></td>
        </tr>
        
        <tr>
            <td align=center><input type=button id=4 value=4
                onclick=selectedBtn(4) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=5 value=5
                onclick=selectedBtn(5) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=6 value=6
                onclick=selectedBtn(6) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=minus value="-"
                onclick=selectedOp("-") style="width: 40pt; height: 30pt"></td>
            <td align=left><input type=button id=sin value="sin"
                onclick=mathText("_sin") style="width: 40pt; height: 30pt"></td>
        </tr>
        <tr>
            <td align=center><input type=button id=7 value=7
                onclick=selectedBtn(7) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=8 value=8
                onclick=selectedBtn(8) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=9 value=9
                onclick=selectedBtn(9) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=multi value=*
                onclick=selectedOp("*") style="width: 40pt; height: 30pt"></td>
            <td align=left><input type=button id=cos value=cos
                onclick=mathText("_cos") style="width: 40pt; height: 30pt"></td>
        </tr>
        <tr>
            <td align=center><input type=button id=0 value=0
                onclick=selectedBtn(0) style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id="plusNMinus" value="+/-"
                onclick=changeSign() style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=dot value="."
                onclick=selectedBtn('.') style="width: 40pt; height: 30pt"></td>
            <td align=center><input type=button id=divide value="/"
                onclick=selectedOp("/") style="width: 40pt; height: 30pt"></td>
            <td align=left><input type=button id=tan value="tan"
                onclick=mathText("_tan") style="width: 40pt; height: 30pt"></td>
        </tr>
    </table>
</body>
</html>
cs

코드설명

 [HTML_17Line] clearAll() : 설정된 변수 및 text value 초기화

 [HTML_19Line] getResult() : 입력된 값 계산 후 result 변수에 저장
 [HTML_24Line] selectedBtn(id) : 선택된 number 버튼의 값을 매개변수로 전달.
 [HTML_30Line] selectedOp(op) : 선택된 operation 버튼의 값을 매개변수로 전달.
 [HTML_45Line] mathText(text) : 선택된 버튼의 값을 매개변수로 전달.

[JS 코드 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<script language="javascript">
    var text1 = "";
    var op = "";
    var text2 = "";
    var result = "";
    var isDotSelected = false;
    
    function selectedBtn(id) {
        if(id==".") {
            isDotSelected = true;
        }
        if (op == "") { //첫번째 피 연산자 구분
            text1 += id;
        } else {
            text2 += id;
        } // end of if ~ else    
        
        document.getElementById('showText').value = document.getElementById('showText').value + id;
        
    } //end of selectedBtn function
    
    function selectedOp(id) {
        op = id;
        document.getElementById('showText').value = text1 + " " + op + " "
    } //end of selectedOp function
    
    function changeSign() {
        if(text1 == "") {
            alert("값이 없습니다.");
            return;
        } 
        
        if(parseFloat(text1) < 0) { // 값이 음수 -> 양수
            if(op == '') { //
                text1 = Math.abs(parseInt(text1));
                document.getElementById('showText').value = text1;
            } else if(parseFloat(text2) < 0) {
                text2 = Math.abs(parseInt(text2));
                document.getElementById('showText').value = text2;
            } 
        } else { //값 양수 -> 음수
            if(op == '') {
                text1 = '-' + text1;
                document.getElementById('showText').value = text1;
            } else {
                text2 = '-'+text2;
                document.getElementById('showText').value = text2;
            }
        }
    }
    
    function mathText(text) {
        if(text1 == "") {
            alert("값이 없습니다.");
        }
        switch(text) {
        case "_sin" :
            result = Math.sin(parseInt(text1));
            document.getElementById('showText').value = text1 + "의 sin 값 : " + result;
            break;
        case "_cos" :
            result = Math.cos(parseInt(text1));
            document.getElementById('showText').value = text1 + "의 cos 값 : " + result;
            break;
        case "_tan" :
            result = Math.tan(parseInt(text1));
            document.getElementById('showText').value = text1 + "의 tan 값 : " + result;
            break;
        }
    }
 
    function clearAll() {
        text1 = "";
        text2 = "";
        op = "";
        result = "";
        document.getElementById('showText').value = "";
    }
    
    function getResult() { //=
        result = text1 + op + text2;
    
        if(isDotSelected) { //실수
            document.getElementById('showText').value = document.getElementById('showText').value + " = " + eval(result).toFixed(3);    
        } else {
            document.getElementById('showText').value = document.getElementById('showText').value + " = " + eval(result);
        }
        
        text1 = eval(result);
        op="";
        text2="";
        result = "";
        
        isDotSelected = false;
        
    } //end of getResult function
    
</script>
cs


<input type=text>에 들어갈 값들을 [text1] [op] [text2] = [result]로 구성하였다.


함수에 공통적으로 들어가 있는 아래의 코드는

document.getElementById('showText').value = document.getElementById('showText').value + ~ ; 

<input type=text>에 값을 입력하기 위한 문장이다.


● isDotSelected 변수는 '.'이 선택되었을 경우 실수로 값을 변경하기 위해 선언한 flag변수이다.


 function selectedBtn(id) { } 에서는 

선택된 버튼을 구분 후 text1 또는 text2에 입력을 해준다.

if (op == "") { //첫번째 피 연산자 구분
            text1 += id;
        } else {
            text2 += id;
        } // end of if ~ else    
        

위의 if문은 들어갈 값이 text1인지 text2인지 확인하기 위한 조건문이다.

만약 op가 공백이 아닐경우 text1은 입력이 된 상태이고 text2의 값을 넣을 것이다.



 function changeSign() { } 에서는 

text1 또는 text2의 값이 양수일 경우 음수로 / 음수일 경우 양수로 변경해주는 함수이다.

function changeSign() {
        if(text1 == "") {
            alert("값이 없습니다.");
            return;
        } 
        
        if(parseFloat(text1) < 0) { // 값이 음수 -> 양수
            if(op == '') { //
                text1 = Math.abs(parseInt(text1));
                document.getElementById('showText').value = text1;
            } else if(parseFloat(text2) < 0) {
                text2 = Math.abs(parseInt(text2));
                document.getElementById('showText').value = text2;
            } 
        } else { //값 양수 -> 음수
            if(op == '') {
                text1 = '-' + text1;
                document.getElementById('showText').value = text1;
            } else {
                text2 = '-'+text2;
                document.getElementById('showText').value = text2;
            }
        }
    }

Line 33 ~ 39 : 값이 음수일 경우 양수로 변경 해주는 조건문이다.

if문 내에 if~else문은 변경할 값이 text1인지 text2인지 확인후 변경 해주는 조건문이다.

Line 41 ~ 49 : 값이 양수일 경우 음수로 변경 해주는 조건문이다.

위의 if문과 마찬가지로 if문 내에 if~else문은 변경할 값이 text1인지 text2인지 확인후 변경 해주는 조건문이다.


● function mathText(text) { } 에서는

매개변수로 넘겨받은 값을 구분 후 sin, cos, tan계산을 해주는 함수이다.

    function mathText(text) {
        if(text1 == "") {
            alert("값이 없습니다.");
        }
        switch(text) {
        case "_sin" :
            result = Math.sin(parseInt(text1));
            document.getElementById('showText').value = text1 + "의 sin 값 : " + result;
            break;
        case "_cos" :
            result = Math.cos(parseInt(text1));
            document.getElementById('showText').value = text1 + "의 cos 값 : " + result;
            break;
        case "_tan" :
            result = Math.tan(parseInt(text1));
            document.getElementById('showText').value = text1 + "의 tan 값 : " + result;
            break;
        }
    }

내장 객체 Math내에 있는 Math.sin  Math.cos  Math.tan를 이용해 각각의 값을 구한다.


● 스크립트 내의 변수들과 HTML의 result를 보여주는 <input type=text>의 값을 초기화 하는 함수이다.

 
    function clearAll() {
        text1 = "";
        text2 = "";
        op = "";
        result = "";
        document.getElementById('showText').value = "";
    }
    


● 지금까지 입력된 값을 계산하는 함수이다.

    function getResult() { //=
        result = text1 + op + text2;
    
        if(isDotSelected) { //실수
            document.getElementById('showText').value = document.getElementById('showText').value + " = " 
+ eval(result).toFixed(3);    
        } else {
            document.getElementById('showText').value = document.getElementById('showText').value + " = " 
+ eval(result);
        }
        
        text1 = eval(result);
        op="";
        text2="";
        result = "";
        
        isDotSelected = false;
        
    } //end of getResult function

text1과 op, text2는 string문자열로 +를 이용해 result 변수에 모두 입력한다.

if조건문을 사용해 실수인지 정수인지 판별하고 조건문 내에서 문자열 result를 eval 내장 함수를 통해 계산한다.

실수 조건문에서 .toFixed(3)함수는 ( )안 숫자 자리수만큼 소수점을 끊어주는 역할을 한다.


★ eval 함수

문자열을 수식으로 바꿔주는 역할을 한다.


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script language="javascript">
 
    var text1 = "10";
    var op = "+";
    var text2 = "20";
    
    var result = text1 + op + text2; // 10+20
    
    alert(eval(result)); //3
</script>
</head>
<body>
 
</body>
</html>
cs

문자열 result를 eval 내장 함수를 통해 수식으로 바꾼 후 바뀐 수식으로 계산 후 출력


반응형

'Web > HTML_JS_CSS' 카테고리의 다른 글

[Javascript] Script 파일의 위치와 onload..  (0) 2019.01.08
[Javascript] Javascript 사용 방법  (0) 2019.01.08
[css] 선택자  (0) 2019.01.07
[JS] 회원가입 유효성 검사  (1) 2018.08.17
[HTML] 회원가입 폼 만들기  (0) 2018.08.17

+ Recent posts