概述
在计算机专业的面试中,面试官往往会针对候选人的编程能力进行一系列的考察。一条常见的便是让候选人找出并修复一个特定的业务逻辑BUG。将详细一个典型的BUG并提供解题思路和答案。
假设有一个在线购物平台,用户可以在平台上购买商品。每个商品都有一个价格,用户在购买时可以选择不同的优惠活动。是一个简化的购物车系统,用于处理用户的订单。在这个系统中,存在一个BUG,需要找出并修复它。
python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
class ShoppingCart:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def calculate_total(self):
total = 0
for product in self.products:
total += product.price
return total
def apply_discount(self, discount_rate):
for product in self.products:
product.price *= (1 – discount_rate)
class Order:
def __init__(self, shopping_cart):
self.shopping_cart = shopping_cart
def place_order(self):
total = self.shopping_cart.calculate_total()
self.shopping_cart.apply_discount(0.1) # Apply a 10% discount
final_total = self.shopping_cart.calculate_total()
print(f"Total amount after discount: {final_total}")
# Usage
shopping_cart = ShoppingCart()
product1 = Product("Laptop", 1000)
product2 = Product("Monitor", 300)
shopping_cart.add_product(product1)
shopping_cart.add_product(product2)
order = Order(shopping_cart)
order.place_order()
要求:
找出并修复上述代码中的BUG,确保在应用折扣后,打印出的总价是正确的。
BUG分析
在这个中,BUG出`ShoppingCart`类中的`apply_discount`方法。该方法应该在计算总价之前应用折扣,而不是像这样在计算总价之后再应用折扣。当打印出总价时,它包含了折扣后的价格,而不是折扣前的价格。
解答思路
为了修复这个BUG,我们需要确保折扣是在计算总价之前应用的。是修改后的代码:
python
class ShoppingCart:
# … (其他方法保持不变)
def apply_discount(self, discount_rate):
for product in self.products:
product.price *= (1 – discount_rate)
def calculate_total(self):
total = 0
for product in self.products:
total += product.price
return total
def place_order(self):
total = self.calculate_total()
self.apply_discount(0.1) # Apply a 10% discount
final_total = self.calculate_total()
print(f"Total amount after discount: {final_total}")
# Usage
# … (使用代码保持不变)
修改后的代码解释
1. 将`apply_discount`方法的调用移动到了`place_order`方法中,确保在计算总价之前应用折扣。
2. 修改`calculate_total`方法,使其在计算总价时不考虑任何折扣。
通过上述分析和修改,我们成功地修复了购物车系统中在应用折扣后的BUG。这个不仅考察了候选人对代码的理解和BUG定位能力,还考察了其解决的能力。在面试中,能够清晰地表达自己的思路和代码修改过程,是给面试官留下良好印象的关键。
还没有评论呢,快来抢沙发~