Menu
Coddy logo textTech

פלט מעוצב

חלק מהיחידה יסודות במסלול ה-Swift של Coddy. שיעור 41 מתוך 86.

challenge icon

אתגר

קל

בשיעור הקודם חישבת כמה כל אדם משלם. עכשיו עצב את הערכים הכספיים כך שיוצגו בדיוק עם 2 ספרות אחרי הנקודה העשרונית, לקבלת פלט מלוטש ומקצועי.

השתמש ב־String(format:) של Swift כדי לעצב את הערכים 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.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)")
        }
    }
}

כל השיעורים ביחידה יסודות

תרגלו בעצמכם: Swift אונליין