서식 지정 출력
Coddy Swift 여정의 기초 섹션에 포함된 레슨. 86개 중 41번째.
챌린지
쉬움이전 수업에서는 각 사람이 얼마를 내는지 계산했습니다. 이제 금액을 소수점 이하 2자리까지 표시하도록 형식을 지정해 깔끔하고 전문적인 결과를 출력하세요.
Swift의 String(format:)을 사용하여 tipAmount, totalWithTip, amountPerPerson 값을 소수점 이하 2자리까지 표시하도록 형식을 지정하세요.
형식 지정자 "%.2f"는 Double을 소수점 이하 2자리까지 형식화합니다.
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]이제 각 금액 앞에 $ 기호가 추가되었으며, 모든 금액이 소수점 이하 2자리까지 표시됩니다.
예를 들어 입력이 85.5, 15, 3이면 출력은 다음과 같아야 합니다.
Welcome to the Bill Split Calculator!
Bill: 85.5
Tip: 15%
People: 3
Tip amount: $12.82
Total with tip: $98.33
Each person pays: $32.77직접 해보기
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)")
}
}
}기초의 모든 레슨
직접 연습해 보세요: Swift 플레이그라운드