Menu
CoddyTech

合計と平均

CoddyのSwiftジャーニー「基礎」セクションの一部。レッスン 81/86。

challenge icon

チャレンジ

簡単

前のレッスンでは、「すべての支出を表示」機能を実装しました。次に、オプション "3" の「合計と平均を表示」機能を実装しましょう。

オプション "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行目に、平均を次の行に出力する

やり取りの例:

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

基礎のすべてのレッスン

自分で練習してみよう: Swiftプレイグラウンド