Menu
CoddyTech

Tổng và trung bình

Thuộc phần Kiến thức nền tảng trong hành trình Swift của Coddy. Bài học 81 trên 86.

challenge icon

Thử thách

Dễ

Trong bài học trước, bạn đã triển khai tính năng "View all expenses". Bây giờ, hãy triển khai tính năng "Show total and average" cho tùy chọn "3".

Chỉnh sửa code để xử lý tùy chọn "3":

  1. Khi người dùng nhập "3", hãy kiểm tra xem mảng expenses có trống không
  2. Nếu mảng trống, hãy in ra No expenses to calculate.
  3. Nếu mảng có khoản chi, hãy tính và hiển thị:
    • Tổng tất cả các khoản chi, theo định dạng Total: $X.X
    • Khoản chi trung bình, theo định dạng Average: $X.X
  4. Tùy chọn "4" vẫn cần in ra Coming soon...
  5. Các tùy chọn "1", "2" và "5" vẫn cần hoạt động như trước

Gợi ý: Dùng reduce(0, +) để tính tổng, rồi chia cho Double(expenses.count) để tính mức trung bình.

Hành vi mong đợi:

  • Khi nhập "3" mà không có khoản chi nào, hãy in ra No expenses to calculate.
  • Khi nhập "3" mà có khoản chi, hãy in tổng trên một dòng và mức trung bình trên dòng tiếp theo

Ví dụ tương tác:

1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
3
No expenses to calculate.
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
20.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
1
Enter expense amount:
30.0
Expense added!
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
3
Total: $50.0
Average: $25.0
1. Add expense
2. View all expenses
3. Show total and average
4. Clear all expenses
5. Exit
5
Goodbye!

Tự làm thử

// Daily Expense Tracker - Menu Display

var expenses: [Double] = []

while true {
    // TODO: Write your code below to print the menu options
    // Each option should be on its own line with the format: "number. option text"
    print("1. Add expense")
    print("2. View all expenses")
    print("3. Show total and average")
    print("4. Clear all expenses")
    print("5. Exit")
    
    let choice = readLine()
    
    if choice == "1" {
        print("Enter expense amount:")
        if let input = readLine(), let amount = Double(input) {
            expenses.append(amount)
            print("Expense added!")
        }
    } else if choice == "2" {
        if expenses.isEmpty {
            print("No expenses recorded.")
        } else {
            print("Your expenses:")
            for expense in expenses {
                print("- $\(expense)")
            }
        }
    } else if choice == "3" {
        print("Coming soon...")
    } else if choice == "4" {
        print("Coming soon...")
    } else if choice == "5" {
        print("Goodbye!")
        break
    } else {
        print("Coming soon...")
    }
}

Tất cả bài học trong Kiến thức nền tảng

Tự luyện tập: Playground Swift