본문 바로가기

콩's EDUCATION/콩's Javascript

Javascript 숙제 3 : 점수 입력 리턴

사용자 숫자 두개와 연산자 이용

: prompt 함수 3개 이용

(form 태그 select 태그 예)

10+20 : 30 리턴 출력 <= add (10,20){}

10-20 : -10 리턴 <= sub(10,20){}

10*20 : 200 리턴 <= mul(10,20){}

10/0 : "오류"리턴 <= div(10,0){}


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>계산기 프로그램</title>
<script type="text/javascript">
var i=0;
var j=0;
var x="";
var flag = 0;

function add(){
    return parseInt(i)+parseInt(j);
}
function sub(){
    return parseInt(i)-parseInt(j);
}
function mul(){
    return parseInt(i)*parseInt(j);
}
function div(){
    if(parseInt(j)==0){
        document.write("다시 입력하세요");
    }else{
    return parseInt(i)/parseInt(j);
    }
}

while(flag==0){
i = prompt("첫번째 숫자 입력 : ");
j = prompt("두번째 숫자 입력 : ");
x = prompt("연산자 입력 : ");

if(isNaN(parseInt(i))== true || isNaN(parseInt(j))== true){
    alert("숫자를 입력하세요.");
    flag=0;
}else{
    if(x=="+"){
           document.write(i+"+"+j+"=");
           document.write(add());
           flag=1;
        }
        else if(x=="-"){
           document.write(i+"-"+j+"=");
           document.write(sub());
           flag=1;
        }
        else if(x=="*"){
           document.write(i+"*"+j+"=");
           document.write(mul());
           flag=1;
        }
        else if(x=="/"){
           document.write(i+"/"+j+"=");
           document.write(div());
           flag=1;
        }
        else{
            alert("입력이 잘못되었습니다.");
            flag=0;
        }
    }
}

</script>
</head>
<body>

</body>
</html>


다른 방법!



<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>계산기</title>

</head>

<body>

<script type="text/javascript">

function add(x, y){

return x + y;

}

function sub(x, y){

return x - y;

}

function mul(x, y){

return x * y;

}

function div(x, y){

return x / y;

}



//var first = prompt("숫자1 입력");

//var op = prompt("연산자 입력");

//var second = prompt("숫자2 입력");



var input = prompt

("숫자1 연산자 숫자2 의 형식으로 입력하세요");

//input = "100 + 200"

var inputArr = input.split(" ", 3);

var firstInt = parseInt(inputArr[0]);

var op = inputArr[1];

var secondInt = parseInt(inputArr[2]);



//op : + - * / 그외의 문자

if(op == "+"){

document.write(add(firstInt,secondInt));

}

else if(op == "-"){

document.write(sub(firstInt, secondInt));

}

else if(op == "*"){

document.write(mul(firstInt, secondInt));

}

else if(op == "/"){

if(div(firstInt, secondInt) == Infinity){

document.write('0으로 나누는 오류 발생');

}

else{

document.write(div(firstInt, secondInt));

}

}

else {

document.write('잘못된 연산자입니다.'+"<br>");

}

</script>

</body>

</html>


calc.html


calc2.html