# U4.5、 實作 ###### tags: `ALG 101` `JavaScript` `2020七月第四週` `進度筆記` `Lidemy心得` `7/21` 找規律,印出金字塔。 --- [LIOJ 1022:印出金字塔](https://oj.lidemy.com/problem/1022) :- 1. 觀察規律,空格用_ : n=1 ``` * ``` n=2 時兩層 ``` _* *** ``` n=3 時三層 ``` __* _*** ***** ``` 會有 n 層。 第 i 層是 2i-1 。 空格數是 n-i 。 星星會置中。 --- 2. 函式填空 ``` for(let i=1; i<=n; i++) { printLayer(i, n) // 把第 i 層跟全部層數傳入; } function printLayer(i, n) { } ``` 3. 加上輔助函式 ``` function repeat(str, n) { let s = '' for(let i = 1; i<=n; i++) { s+=str } return s } ``` 4. 按照規律填答案 ``` for(let i=1; i<=n; i++) { printLayer(i, n) // 把第 i 層跟全部層數傳入; } function printLayer(i, n) { // _ + stars ; let str = repeat('', n-i)+repeat('*', 2*i-1) console.log(str) } function repeat(str, n) { let s = '' for(let i = 1; i<=n; i++) { s+=str } return s } ``` Done~ --- # U4.6、 實作 九九乘法表 ###### tags: `ALG 101` `JavaScript` `2020七月第四週` `進度筆記` `Lidemy心得` `7/21` 經典的題型。 --- ```` 1*1=1 1*1=2 2*1=2 . . ```` 給範圍,印出值: ``` function printnNMT(x) { // 把 1*幾 換成 x*幾; for(let i=1; i<=9; i++) { // 產生 1~9 ; let n = '' console.log(x+ '*'+ i + '=' +x*i) // 印出 1*1 ~ 1*9 = x*i 結果; } } /* printnNmt(1) printnNmt(2) printnNmt(3) . . ... 原來是迴圈,於是就替換成: */ for (let x=1; x<=9; x++) { //產生 1*1~9*9 ; printnNMT(x) // 把 x 傳進去函式; } ``` 會先跑函式外的迴圈,再跑函式內的迴圈。 --- --- # U4.7、 實作 平方數 ###### tags: `ALG 101` `JavaScript` `2020七月第四週` `進度筆記` `Lidemy心得` `7/21` --- ## 找出 1~100 , 某個正整數的平方數 簡化法,印出 1~100 。 ``` for(let i=1; i<=100; i++) { console.log(i) } ``` 函式填空: ``` function isSquare(n) { // 判斷 i 是不是平方數; } ``` 怎麼判斷平方數? 開根號: Math.sqrt(n) 無條件捨去: Math.floor(n) 放上邏輯判斷: ``` for (let i=1; i<=100; i++) { if (isSquare(i)) { console.log(i) } } function isSquare(n) { let root = Math.floor(Math.sqrt(n)) // root 的平方根是 Math.floor 開根號後無條件捨去; return root * root === n // 判是是 true or falsr 後再回傳; } /* let i=1 while(i*i <= 100) { console.log(i*i) i++ } */ ``` 看 1~100 間的每個數是不是平方數。 --- ## 也可以印出平方數到超過 100 為止: ``` let i=1 while(i*i <= 100) { console.log(i*i) i++ } ``` 直接計算每個平方數,直到超過 100 就停止。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up