Menu
Coddy logo textTech

합계 및 평균

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

challenge icon

챌린지

쉬움

이전 레슨에서는 "View all expenses" 기능을 구현했습니다. 이제 옵션 "3"에 대한 "Show total and average" 기능을 구현해 보세요.

옵션 "3"을 처리하도록 코드를 수정하세요:

  1. 사용자가 "3"을 입력하면, expenses 배열이 비어 있는지 확인합니다.
  2. 배열이 비어 있으면, No expenses to calculate.를 출력합니다.
  3. 배열에 지출 내역이 있으면, 다음을 계산하고 표시합니다:
    • 모든 지출의 합계, Total: $X.X 형식으로 출력
    • 평균 지출, Average: $X.X 형식으로 출력
  4. 옵션 "4"는 여전히 Coming soon...을 출력해야 합니다.
  5. 옵션 "1", "2", "5"는 이전과 동일하게 작동해야 합니다.

힌트: 합계를 계산하려면 reduce(0, +)를 사용하고, 평균을 구하려면 Double(expenses.count)로 나눕니다.

예상 동작:

  • 지출 내역이 없을 때 "3"을 입력하면, No expenses to calculate.를 출력합니다.
  • 지출 내역이 있을 때 "3"을 입력하면, 한 줄에는 합계를, 다음 줄에는 평균을 출력합니다.

상호작용 예시:

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!

직접 해보기

// 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...")
    }
}

기초의 모든 레슨