HOMEWORK

DAY 33 - JS HOMEWORK - 덧셈문제 (2024.08.19)

summ.n 2024. 8. 22. 09:26

Math.floor(Math.random() * 10) + 1;

Math.random() 함수의 결과는 0~0.99999...이고,

Math.random() * 10 의 결과는 0~9.99999...입니다.

따라서, Math.floor(Math.random() * 10)의 결과는 0~9 범위의 정수이다.

우리가 원하는 범위는 1~10 사이이므로  Math.floor(Math.random() * 10) + 1을 해주면 된다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>1~10 사이의 덧셈 문제를 발생합니다. </h3>
	<input type="button" value="문제 생성" onclick="start()"/>
	<h3><span id="x">x</span> + <span id="y">y</span> = <span id="question">?</span></h3>
	<input type="button" value="결과 보기" onclick="printResult()"/>
<script type="text/javascript">
var x;
var y;

function start(){
	document.getElementById("question").innerText = "?";
	x = Math.floor(Math.random() * 10) + 1;
	y = Math.floor(Math.random() * 10) + 1;	
	
	document.getElementById("x").innerText = x;
	document.getElementById("y").innerText = y;
}

function sum(x, y){
	return x + y;
}

function printResult(){
	var result = sum(x,y);
	document.getElementById("question").innerText = result;
}
</script>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>1~10 사이의 덧셈 문제를 발생합니다. </h3>
	<input type="button" value="문제 생성" onclick="start()"/>
	<h3><span id="x">x</span> + <span id="y">y</span> = <span id="question">?</span></h3>
	<input type="button" value="결과 보기" onclick="printResult()" />
<script type="text/javascript">
var x;
var y;

function start(){
	document.getElementById("question").innerText = "?";
	x = Math.floor(Math.random() * 10) + 1;
	y = Math.floor(Math.random() * 10) + 1;	
	
	document.getElementById("x").innerText = x;
	document.getElementById("y").innerText = y;
}

function sum(x, y){
	return x + y;
}

function printResult(){
	var result = sum(x,y);
	document.getElementById("question").innerHTML = '<span style="color:red;">' + result + '</span>';
}
</script>
</body>
</html>
document.getElementById("question").innerHTML = "<font color='red'>" + result + "</font>";
document.getElementById("question").innerHTML = '<span style="color:red;">' + result + '</span>';

 결과보기 버튼 눌렀을 때 정답이 빨간 글씨로 나오게 하는 것을 깜빡해쑤다~

 <span> 태그 이용해서 하는 방법이 더 좋다 !!