Menu
CoddyTech

مخرجات منسقة

جزء من قسم الأساسيات في رحلة Swift على Coddy. الدرس 41 من 86.

challenge icon

التحدي

سهل

في الدرس السابق، حسبتَ المبلغ الذي يدفعه كل شخص. الآن، نسّق القيم النقدية لعرض منزلتين عشريتين بالضبط، للحصول على مخرجات احترافية ومصقولة.

استخدم String(format:) في Swift لتنسيق القيم 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.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)")
        }
    }
}

جميع دروس الأساسيات

تدرّب بنفسك: Playground لـ Swift