Bibi's DevLog ๐Ÿค“๐ŸŽ

[๋ฐฑ์ค€ 6322] ์ง๊ฐ ์‚ผ๊ฐํ˜•์˜ ๋‘ ๋ณ€ (Swift) ๋ณธ๋ฌธ

ํ”„๋กœ๊ทธ๋ž˜๋ฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด Swift

[๋ฐฑ์ค€ 6322] ์ง๊ฐ ์‚ผ๊ฐํ˜•์˜ ๋‘ ๋ณ€ (Swift)

๋น„๋น„ bibi 2022. 11. 21. 18:11

6322๋ฒˆ: ์ง๊ฐ ์‚ผ๊ฐํ˜•์˜ ๋‘ ๋ณ€

  • a์ œ๊ณฑ + b์ œ๊ณฑ = c์ œ๊ณฑ ์„ ๋งŒ์กฑํ•˜๋Š” ์–‘์ˆ˜ a, b, c ๊ตฌํ•˜๊ธฐ
    • abc ์ค‘ 2๊ฐœ๋Š” ์ž์—ฐ์ˆ˜๋กœ ์ฃผ์–ด์ง
    • ๋ฏธ์ง€์ˆ˜๊ฐ€ a๋ผ๋ฉด
      • a = ์ œ๊ณฑ๊ทผ(c์ œ๊ณฑ - b์ œ๊ณฑ)
    • ๋ฏธ์ง€์ˆ˜๊ฐ€ b๋ผ๋ฉด
      • b = ์ œ๊ณฑ๊ทผ(c์ œ๊ณฑ - a์ œ๊ณฑ)
    • ๋ฏธ์ง€์ˆ˜๊ฐ€ c๋ผ๋ฉด
      • c = ์ œ๊ณฑ๊ทผ(a์ œ๊ณฑ + b์ œ๊ณฑ)
  • ์ œ๊ณฑ๊ทผ ์•ˆ์˜ ์ˆ˜๊ฐ€ 0๋ณด๋‹ค “์ž‘๊ฑฐ๋‚˜”(์Œ์ˆ˜), 0์ผ ๋•Œ ์ง๊ฐ์‚ผ๊ฐํ˜•์„ ๋งŒ๋“ค ์ˆ˜ ์—†๋‹ค.
    • ์Œ์ˆ˜ ์กฐ๊ฑด ๋ฟ ์•„๋‹ˆ๋ผ 0์ด ๋˜๋Š” ์กฐ๊ฑด๋„ ๋”ฐ์ ธ์•ผ ํ•จ์— ์œ ์˜
  • Swift์˜ sqrt() ํ•จ์ˆ˜๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ์Œ์ˆ˜์ผ ๋•Œ nan์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
    • nan์€ type(of:) ๋กœ ํŒ๋ณ„ํ–ˆ์„ ๋• Double์ด์ง€๋งŒ, == ๋กœ ํŒ๋ณ„ํ•  ์ˆ˜ ์—†๋‹ค.
    • ๊ทธ๋ž˜์„œ ์ผ๋‹จ sqrt() ๋‚ด๋ถ€์— ๋„ฃ์„ ์ˆ˜๊ฐ€ 0๋ณด๋‹ค ํฐ์ง€ ํŒ๋ณ„ํ•ด์„œ ํ’€์—ˆ๋‹ค.
    • ๊ณต์‹๋ฌธ์„œ๋ฅผ ์ฐพ์•„๋ณด๋‹ˆ Double.nan ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๊ณ , == ๋Œ€์‹  isNan ์œผ๋กœ ํŒ๋ณ„ํ•˜๋ผ๊ณ  ํ•œ๋‹ค!
    • https://developer.apple.com/documentation/swift/floatingpoint/nan
  • ์ถœ๋ ฅ ํ˜•์‹์—์„œ ๋นˆ ์ค„ ์ถœ๋ ฅ์— ์œ ์˜

ํ’€์ด

import Foundation
var count = 0
while true {
    let input = readLine()!
    if input == "0 0 0" {
        break
    }
    if count > 0 {
        print("")
    }
    let inputArr = input.split(separator: " ").map { Int($0)! }
    let a = inputArr[0]
    let b = inputArr[1]
    let c = inputArr[2]
    if a < 0 {
        let answer = Double(c*c - b*b)
        print("Triangle #\(count + 1)")
        if answer <= 0 {
            print("Impossible.")
        } else {
            print("a = \(String(format: "%.3f", sqrt(answer)))")
        }
    }
    if b < 0 {
        let answer = Double(c*c - a*a)
        print("Triangle #\(count + 1)")
        if answer <= 0 {
            print("Impossible.")
        } else {
            print("b = \(String(format: "%.3f", sqrt(answer)))")
        }
    }
    if c < 0 {
        let answer = Double(a*a + b*b)
        print("Triangle #\(count + 1)")
        if answer <= 0 {
            print("Impossible.")
        } else {
            print("c = \(String(format: "%.3f", sqrt(answer)))")
        }
    }
    count += 1
}