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

[๋ฐฑ์ค€ 5613] ๊ณ„์‚ฐ๊ธฐ ํ”„๋กœ๊ทธ๋žจ ๋ณธ๋ฌธ

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

[๋ฐฑ์ค€ 5613] ๊ณ„์‚ฐ๊ธฐ ํ”„๋กœ๊ทธ๋žจ

๋น„๋น„ bibi 2022. 11. 10. 12:43

5613๋ฒˆ: ๊ณ„์‚ฐ๊ธฐ ํ”„๋กœ๊ทธ๋žจ

์ฒซ ์ž…๋ ฅ์€ ๊ทธ๋ƒฅ ์ €์žฅ๋˜๊ณ ,

์—ฐ์‚ฐ์ž๋Š” ์ž…๋ ฅ๋งˆ๋‹ค ์ €์žฅํ•˜๊ณ ,

๊ทธ ๋‹ค์Œ๋ถ€ํ„ฐ ์ˆซ์ž๊ฐ€ ๋“ค์–ด์˜ฌ ๋•Œ ๋งˆ๋‹ค ๊ฒฐ๊ณผ๊ฐ’์ด ๋ฐ”๋€Œ์–ด์•ผ ํ•œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด 1 + 1 ์„ ๊ณ„์‚ฐํ•  ๋•Œ

  • 1์€ ์ฒซ ์ž…๋ ฅ์ด๋ฏ€๋กœ ๊ฒฐ๊ณผ๊ฐ’์— ๊ทธ๋ƒฅ ์ €์žฅ
    • ์€ ์—ฐ์‚ฐ์ž์ด๋ฏ€๋กœ ์—ฐ์‚ฐ์ž๋กœ ์ €์žฅ
  • 1์ด ๋“ค์–ด์˜ค๋ฉด ๊ธฐ์กด ๊ฒฐ๊ณผ๊ฐ’์— ์—ฐ์‚ฐ์ž๋ฅผ ํ™œ์šฉํ•ด 1์„ ๊ณ„์‚ฐํ•ด์•ผ ํ•จ โ†’ ๊ฒฐ๊ณผ๊ฐ’ ๊ฐฑ์‹ 

ํ’€์ด

var currentResult = 0
var currentOperator = ""
while let input = readLine() {
    guard let intInput = Int(input) else { // ์ž…๋ ฅ์ด ์—ฐ์‚ฐ์ž์ธ์ง€ ์ˆซ์ž์ธ์ง€ ํŒ๋‹จ
        if input == "=" {
            break
        } else {
            currentOperator = input
            continue
        }
    }
    switch currentOperator {
        case "+":
        currentResult += intInput
        case "-":
        currentResult -= intInput
        case "*":
        currentResult *= intInput
        case "/":
        currentResult /= intInput
        default: // ""์ธ ๊ฒฝ์šฐ = ์ฒซ ์ž…๋ ฅ
        currentResult = intInput
        continue
    }
}
print(currentResult)

๋‹ค๋ฅธ ํ’€์ด

๋‚˜๋Š” ์ž…๋ ฅ ํ•œ ์ค„์„ ๋ฐ˜๋ณต๋‹จ์œ„๋กœ ์‚ผ์•˜๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ํ•˜์‹  ๋ถ„๋„ ์žˆ์—ˆ๋‹ค!

  • ์ฒซ ์ž…๋ ฅ์€ ๊ทธ๋ƒฅ ๋ฐ›๊ธฐ (readLine())
  • ์ดํ›„ ์ž…๋ ฅ๋ถ€ํ„ฐ โ€œ์—ฐ์‚ฐ์ž, ์ˆซ์žโ€ ๋‹จ์œ„๋กœ ๋ฐ˜๋ณตํ•ด ๊ณ„์‚ฐ

์‹œ๊ฐ„๋ณต์žก๋„๋Š” ๊ฐ™์ง€๋งŒ, ์ด์ชฝ์ด ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์กฐ๊ธˆ ๋œ ์‚ฌ์šฉํ•œ๋‹ค.

var num = Int(readLine()!)!
var sum = num
while true {
    let operators = readLine()!
    if operators == "=" {
        break
    }
    num = Int(readLine()!)!
    switch operators {
    case "+":
        sum += num
    case "-":
        sum -= num
    case "*":
        sum *= num
    case "/":
        sum /= num
    default:
        break
    }
}
print(sum)