Menu
Coddy logo textTech

할인 적용하기

Coddy Dart 여정의 로직 & 흐름 섹션에 포함된 레슨 — 65개 중 36번째.

challenge icon

챌린지

쉬움

적격 주문에 대해 백분율 기반 할인을 적용하는 할인 시스템을 구현하여 쇼핑카트 계산기 프로젝트를 이어가는 프로그램을 작성하세요. 이전 레슨의 총 비용 계산을 바탕으로, 프로그램은 다음을 수행해야 합니다:

  1. 이전 설정의 기존 제품 카탈로그 Map과 쇼핑카트 기능을 사용합니다.
  2. 고객이 카트에 추가하려는 항목을 나타내는 여러 문자열 입력을 읽습니다 (입력은 "cart_done"을 받으면 종료됩니다).
  3. 각 항목에 대해 containsKey()를 사용하여 제품 카탈로그에 존재하는지 확인하고 유효한 항목을 카트에 추가합니다.
  4. 카트에 담긴 모든 항목의 가격을 합산하여 소계(subtotal)를 계산합니다.
  5. 할인 임계값(threshold amount)을 나타내는 문자열 입력을 읽습니다.
  6. 적용할 할인율(percentage)을 나타내는 문자열 입력을 읽습니다.
  7. 소계가 임계값 이상인 경우에만 할인을 적용합니다.
  8. 할인 적용 후의 할인 금액과 최종 합계를 계산합니다.
  9. 아래에 표시된 정확한 형식으로 할인 계산 보고서를 표시합니다.

예를 들어, 상점에 1.50"Apple", 0.80"Banana", 2.00"Orange", 3.25"Milk" 제품이 있고, 고객이 "Apple", "Orange", "Milk", "Apple"을 추가하고 싶어 하며, 할인 임계값이 5.00이고 할인율이 10인 경우, 프로그램은 다음과 같이 출력해야 합니다:

Shopping Cart Operations:
Adding 'Apple': Item added to cart successfully
Adding 'Orange': Item added to cart successfully
Adding 'Milk': Item added to cart successfully
Adding 'Apple': Item added to cart successfully
Cart Contents: [Apple, Orange, Milk, Apple]
Cost Calculation:
Apple: $1.50
Orange: $2.00
Milk: $3.25
Apple: $1.50
Subtotal: $8.25
Discount Analysis:
Threshold: $5.00
Discount Rate: 10%
Subtotal ($8.25) meets threshold requirement
Discount Applied: $0.83
Final Total: $7.42
Cart Summary:
Total items in cart: 4
Unique products in cart: 3
Items successfully added: 4
Items not found: 0
Discount Status: 10% discount applied
Cart Status: Ready for checkout

상점에 999.99"Laptop", 25.50"Mouse", 75.00"Keyboard" 제품이 있고, 고객이 "Mouse", "Keyboard"를 추가하고 싶어 하며, 할인 임계값이 150.00이고 할인율이 15인 경우, 프로그램은 다음과 같이 출력해야 합니다:

Shopping Cart Operations:
Adding 'Mouse': Item added to cart successfully
Adding 'Keyboard': Item added to cart successfully
Cart Contents: [Mouse, Keyboard]
Cost Calculation:
Mouse: $25.50
Keyboard: $75.00
Subtotal: $100.50
Discount Analysis:
Threshold: $150.00
Discount Rate: 15%
Subtotal ($100.50) does not meet threshold requirement
Discount Applied: $0.00
Final Total: $100.50
Cart Summary:
Total items in cart: 2
Unique products in cart: 2
Items successfully added: 2
Items not found: 0
Discount Status: No discount applied
Cart Status: Ready for checkout

상점에 12.99"Novel", 4.50"Magazine", 89.00"Textbook" 제품이 있고, 고객이 "Novel", "Textbook", "Magazine", "Novel"을 추가하고 싶어 하며, 할인 임계값이 75.00이고 할인율이 20인 경우, 프로그램은 다음과 같이 출력해야 합니다:

Shopping Cart Operations:
Adding 'Novel': Item added to cart successfully
Adding 'Textbook': Item added to cart successfully
Adding 'Magazine': Item added to cart successfully
Adding 'Novel': Item added to cart successfully
Cart Contents: [Novel, Textbook, Magazine, Novel]
Cost Calculation:
Novel: $12.99
Textbook: $89.00
Magazine: $4.50
Novel: $12.99
Subtotal: $119.48
Discount Analysis:
Threshold: $75.00
Discount Rate: 20%
Subtotal ($119.48) meets threshold requirement
Discount Applied: $23.90
Final Total: $95.58
Cart Summary:
Total items in cart: 4
Unique products in cart: 3
Items successfully added: 4
Items not found: 0
Discount Status: 20% discount applied
Cart Status: Ready for checkout

프로그램은 먼저 소계를 계산한 다음, 조건문 if를 사용하여 할인 임계값을 충족하는지 확인해야 합니다. 임계값이 충족되면 소계에 할인율을 100으로 나눈 값을 곱하여 할인 금액을 계산합니다. 소계에서 할인 금액을 빼서 최종 합계를 구합니다. 모든 통화 값은 소수점 이하 2자리까지 정확하게 표시되도록 형식을 지정하세요. 입력 형식은 다음과 같습니다: "cart_done"으로 끝나는 카트에 추가할 항목 이름들, 이어서 할인 임계값과 할인율(둘 다 적절한 숫자 유형으로 변환해야 하는 문자열)입니다.

직접 해보기

import 'dart:io';

void main() {
  // Product catalog with prices
  Map<String, double> products = {
    'Apple': 1.50,
    'Banana': 0.80,
    'Orange': 2.00,
    'Milk': 3.25,
    'Laptop': 999.99,
    'Mouse': 25.50,
    'Keyboard': 75.00,
    'Novel': 12.99,
    'Magazine': 4.50,
    'Textbook': 89.00
  };
  
  // Shopping cart list
  List<String> cart = [];
  
  // Counters for summary
  int itemsAdded = 0;
  int itemsNotFound = 0;
  
  print('Shopping Cart Operations:');
  
  // Read items until "cart_done"
  String? item;
  while ((item = stdin.readLineSync()) != 'cart_done') {
    if (item != null) {
      if (products.containsKey(item)) {
        cart.add(item);
        print("Adding '$item': Item added to cart successfully");
        itemsAdded++;
      } else {
        print("Adding '$item': Item not available in store");
        itemsNotFound++;
      }
    }
  }
  
  // Display cart contents
  print('Cart Contents: $cart');
  
  // Calculate total cost
  print('Cost Calculation:');
  double totalCost = 0.0;
  
  for (String cartItem in cart) {
    double price = products[cartItem]!;
    totalCost += price;
    print('$cartItem: \$${price.toStringAsFixed(2)}');
  }
  
  print('Total Cost: \$${totalCost.toStringAsFixed(2)}');
  
  // Cart summary
  Set<String> uniqueProducts = cart.toSet();
  print('Cart Summary:');
  print('Total items in cart: ${cart.length}');
  print('Unique products in cart: ${uniqueProducts.length}');
  print('Items successfully added: $itemsAdded');
  print('Items not found: $itemsNotFound');
  print('Cart Status: Ready for checkout');
}

로직 & 흐름의 모든 레슨