背景
在计算机专业面试中,业务逻辑BUG的识别与解决是一项重要的考察。这类往往要求者不仅要有扎实的编程基础,还要有良逻辑思维能力和解决能力。是一个典型的面试题,我们将详细解析其及解决方案。
面试题
在一个在线图书销售系统中,用户可以浏览图书、添加购物车、结算订单。系统在结算时,根据用户选择的支付计算折扣。为系统部分代码:
python
class BookStore:
def __init__(self):
self.books = [{'id': 1, 'title': 'Python编程', 'price': 99.99},
{'id': 2, 'title': '数据结构与算法', 'price': 89.99},
{'id': 3, 'title': '机器学习', 'price': 79.99}]
def get_book_price(self, book_id):
for book in self.books:
if book['id'] == book_id:
return book['price']
return 0
def calculate_discount(self, payment_method):
if payment_method == 'credit_card':
return 0.1 # 10%折扣
elif payment_method == 'cash':
return 0.05 # 5%折扣
else:
return 0 # 没有折扣
def checkout(self, book_ids, payment_method):
total_price = sum(self.get_book_price(book_id) for book_id in book_ids)
discount = self.calculate_discount(payment_method)
discounted_price = total_price * (1 – discount)
return discounted_price
# 示例用法
book_store = BookStore()
print(book_store.checkout([1, 2, 3], 'cash')) # 应输出:79.99
在上述代码中,存在一个业务逻辑BUG。请找出这个BUG,并说明原因。提供一个修改后的代码段,以修复这个BUG。
BUG分析与修复
分析:
在上述代码中,`calculate_discount`方法根据不同的支付返回不同的折扣。当支付为'cash'时,返回的折扣为0.05,即5%的折扣。这意味着用户使用现金支付时,应享受5%的折扣,但代码中的折扣计算却是正确的。
BUG在于`checkout`方法中,当用户选择'cash'支付时,计算出的价格并没有减少5%。这是因为`calculate_discount`方法返回的是折扣比例,而不是折扣金额。在计算`discounted_price`时,应该使用`total_price * (1 – discount)`,而不是`total_price – total_price * discount`。
修复:
为了修复这个BUG,我们需要修改`calculate_discount`方法,使其返回折扣金额,而不是折扣比例。是修改后的代码段:
python
class BookStore:
# …(其他方法保持不变)
def calculate_discount(self, payment_method):
if payment_method == 'credit_card':
return 10 # 10元折扣
elif payment_method == 'cash':
return 5 # 5元折扣
else:
return 0 # 没有折扣
def checkout(self, book_ids, payment_method):
total_price = sum(self.get_book_price(book_id) for book_id in book_ids)
discount = self.calculate_discount(payment_method)
discounted_price = total_price – discount
return discounted_price
# 示例用法
book_store = BookStore()
print(book_store.checkout([1, 2, 3], 'cash')) # 应输出:79.99
通过这种,当用户选择'cash'支付时,价格会减少5元,从而实现了预期的折扣效果。
在解决业务逻辑BUG时,关键在于理解业务需求和代码逻辑。通过仔细分析代码和业务规则,我们可以找出并修复BUG。在这个面试题中,我们通过识别折扣计算的错误,并修改相关代码,成功修复了BUG。这对于计算机专业的者来说,是一个很实践案例。
还没有评论呢,快来抢沙发~