Created
June 10, 2015 05:35
-
-
Save ihower/a12d2b174fbe4fa049d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# http://blog.orangeapple.tw/posts/what-is-computational-thinking/ | |
# 設計一個「從0開始慢慢找出X」的流程 (設計演算法),如下: | |
# 1. 先寫下“輸入=17”、“答案=0”、“位數=1” | |
# 2. 把“答案”乘以自己,看看有沒有超過“輸入”: | |
# 2-1. 是:將“答案”減“位數”,跳到第3步 | |
# 2-2. 否:將“答案”加“位數”,跳回第2步 | |
# 3. 看看“答案”乘上“答案”的結果與“輸入”是否相差0.1以內: | |
# 3-1. 是:跳到第4步 | |
# 3-2. 否:將“位數”除以10,跳回第2步 | |
# 4. 此時“答案”即為“輸入”的平方根近似值,流程結束 | |
# puts Math.sqrt(17) | |
def solution(n) | |
# Step 1 | |
answer = 0 | |
digital = 1.0 | |
sqrt = answer * answer | |
while ( (n - sqrt).abs > 0.1 ) # Step 3 | |
while ( sqrt < n ) do # Step 2 | |
answer += digital | |
sqrt = answer * answer | |
end | |
answer -= digital | |
sqrt = answer * answer | |
digital = digital / 10 | |
end | |
return answer # Step 4 | |
end | |
puts solution(17) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Orz
Float problem ?
but
5.0*5.0 #=> 25.0