-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction.js
More file actions
88 lines (65 loc) ยท 2.2 KB
/
function.js
File metadata and controls
88 lines (65 loc) ยท 2.2 KB
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
// function ๊ธฐ์ด ์ฐ์ต
// ์ฐธ๊ณ : ํจ์ | https://ko.javascript.info/function-basics
/*
['?'๋ '||'๋ฅผ ์ฌ์ฉํ์ฌ ํจ์ ๋ค์ ์์ฑํ๊ธฐ]
์๋ ํจ์๋ ๋งค๊ฐ๋ณ์ age๊ฐ 18๋ณด๋ค ํฐ ๊ฒฝ์ฐ true๋ฅผ ๋ฐํํฉ๋๋ค.
๊ทธ ์ด์ธ์ ๊ฒฝ์ฐ๋ ์ปจํ ๋ํ์์๋ฅผ ํตํด ์ฌ์ฉ์์๊ฒ ์ง๋ฌธํ ํ, ํด๋น ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํฉ๋๋ค.
function checkAge(age) {
if (age > 18) {
return true;
} else {
return confirm('๋ณดํธ์์ ๋์๋ฅผ ๋ฐ์ผ์
จ๋์?');
}
}
if๋ฌธ์ ์ฌ์ฉํ์ง ์๊ณ ๋์ผํ ๋์์ ํ๋ ํจ์๋ฅผ ํ ์ค์ ์์ฑํด๋ณด์ธ์.
*/
// ๋ฌผ์ํ ์ฐ์ฐ์ ?๋ฅผ ์ฌ์ฉํ์ฌ ๋ณธ๋ฌธ์ ์์ฑ
function checkAge(age) {
return age > 18 ? true : confirm("๋ณดํธ์์ ๋์๋ฅผ ๋ฐ์ผ์
จ๋์?");
}
// OR ์ฐ์ฐ์ ||๋ฅผ ์ฌ์ฉํ์ฌ ๋ณธ๋ฌธ์ ์์ฑ
function checkAge2(age) {
return age > 18 || confirm("๋ณดํธ์์ ๋์๋ฅผ ๋ฐ์ผ์
จ๋์?");
}
/*
min(a, b) ํจ์ ๋ง๋ค๊ธฐ
a์ b ์ค ์์ ๊ฐ์ ๋ฐํํด์ฃผ๋ ํจ์, min(a,b)์ ๋ง๋ค์ด๋ณด์ธ์.
min(2, 5) == 2
min(3, -1) == -1
min(1, 1) == 1
*/
function min(a, b) {
return a <= b ? a : b;
}
/*
pow(x,n) ํจ์ ๋ง๋ค๊ธฐ
x์ n์ ๊ณฑ์ ๋ฐํํด์ฃผ๋ ํจ์, pow(x,n)๋ฅผ ๋ง๋ค์ด๋ณด์ธ์. x์ n ์ ๊ณฑ์ x๋ฅผ n๋ฒ ๊ณฑํด์ ๋ง๋ค ์ ์์ต๋๋ค.
pow(3, 2) = 3 * 3 = 9
pow(3, 3) = 3 * 3 * 3 = 27
pow(1, 100) = 1 * 1 * ...* 1 = 1
ํ๋กฌํํธ ๋ํ์์๋ฅผ ๋์ ์ฌ์ฉ์๋ก๋ถํฐ x์ n์ ์
๋ ฅ๋ฐ๊ณ pow(x,n)์ ๋ฐํ ๊ฐ์ ๋ณด์ฌ์ฃผ๋ ์ฝ๋๋ฅผ ์์ฑํด ๋ณด์ธ์.
์ฃผ์์ฌํญ: n์ 1 ์ด์์ ์์ฐ์์ด์ด์ผ ํฉ๋๋ค. ์ด์ธ์ ๊ฒฝ์ฐ์ ์์ฐ์๋ฅผ ์
๋ ฅํ๋ผ๋ ์ผ๋ฟ ์ฐฝ์ ๋์์ฃผ์ด์ผ ํฉ๋๋ค.
*/
// ๊ฑฐ๋ญ์ ๊ณฑ ์ฐ์ฐ์ ์ฌ์ฉ
function pow(x, n) {
x **= n;
if (n < 1) throw new Error(`${n}์ ์์ ์ ์์ด์ด์ผ ํฉ๋๋ค.`);
return x;
}
// let x = prompt("x?", "");
// let n = prompt("n?", "");
// console.log(`pos(${x}, ${n}) = ${pow(x, n)}`);
// ๊ฑฐ๋ญ์ ๊ณฑ ์ฐ์ฐ์ ๋ฏธ์ฌ์ฉ
function pow(x, n) {
if (n < 1) throw new Error(`${n}์ ์์ ์ ์์ด์ด์ผ ํฉ๋๋ค.`);
let result = x;
let i = 1;
while (i < n) {
result *= x;
i++;
}
return result;
}
let x = prompt("x?", '');
let n = prompt("n?", '');
console.log(pow(x, n));