Menu
Coddy logo textTech

형식화된 출력

Coddy Swift 여정의 기초 섹션에 포함된 레슨 — 86개 중 41번째.

challenge icon

챌린지

쉬움

이전 레슨에서는 각 사람이 지불해야 할 금액을 계산했습니다. 이제 세련되고 전문적인 출력을 위해 통화 값을 소수점 둘째 자리까지 정확하게 표시하도록 형식을 지정해 보겠습니다.

Swift의 String(format:)을 사용하여 tipAmount, totalWithTip, 그리고 amountPerPerson 값을 소수점 둘째 자리까지 표시하도록 형식을 지정하세요.

형식 지정자 "%.2f"Double을 소수점 둘째 자리까지 형식화합니다:

let formatted = String(format: "%.2f", someDouble)

다음과 같은 정확한 형식으로 출력되도록 업데이트하세요:

Welcome to the Bill Split Calculator!
Bill: [billTotal]
Tip: [tipPercentage]%
People: [numberOfPeople]
Tip amount: $[tipAmount formatted]
Total with tip: $[totalWithTip formatted]
Each person pays: $[amountPerPerson formatted]

각 통화 값 앞에 $ 기호가 추가되었으며, 모든 금액이 소수점 둘째 자리까지 정확하게 표시되는 것을 확인하세요.

예를 들어, 입력값이 85.5, 15, 그리고 3인 경우 출력은 다음과 같아야 합니다:

Welcome to the Bill Split Calculator!
Bill: 85.5
Tip: 15%
People: 3
Tip amount: $12.83
Total with tip: $98.33
Each person pays: $32.78

직접 해보기

print("Welcome to the Bill Split Calculator!")

if let billInput = readLine(), let billTotal = Double(billInput) {
    if let tipInput = readLine(), let tipPercentage = Int(tipInput) {
        if let peopleInput = readLine(), let numberOfPeople = Int(peopleInput) {
            let tipAmount = billTotal * Double(tipPercentage) / 100
            let totalWithTip = billTotal + tipAmount
            let amountPerPerson = totalWithTip / Double(numberOfPeople)
            
            print("Bill: \(billTotal)")
            print("Tip: \(tipPercentage)%")
            print("People: \(numberOfPeople)")
            print("Tip amount: \(tipAmount)")
            print("Total with tip: \(totalWithTip)")
            print("Each person pays: \(amountPerPerson)")
        }
    }
}

기초의 모든 레슨