文章详情

背景介绍

在计算机专业的面试中,业务逻辑BUG的定位与修复是一个常见的考察点。这类旨在考察者对编程逻辑的理解、分析和解决能力。是一个具体的面试及其解答过程。

面试

假设你正在开发一个在线购物网站,有一个业务功能:用户可以在购物车中添加商品,进行结算。在结算过程中,系统会根据用户选择的支付自动计算支付金额。代码片段负责计算支付金额:

python

class ShoppingCart:

def __init__(self):

self.items = []

def add_item(self, item, price):

self.items.append((item, price))

def calculate_total(self, payment_method):

total = 0

if payment_method == 'credit':

total = sum(price * 1.1 for item, price in self.items) # 假设信用卡支付需要额外收取10%的手续费

elif payment_method == 'cash':

total = sum(price for item, price in self.items)

else:

raise ValueError("Unsupported payment method")

return total

# 测试代码

cart = ShoppingCart()

cart.add_item("Laptop", 1000)

cart.add_item("Mouse", 50)

print(cart.calculate_total('credit')) # 应输出1110

print(cart.calculate_total('cash')) # 应输出1050

来了:在上述代码中存在一个BUG,导致使用信用卡支付时计算出的总金额比实际金额多出了110元。请定位并修复这个BUG。

解答过程

我们需要分析BUG的可能原因。在这个例子中,BUG可能出几个地方:

1. 信用卡支付手续费的计算:是否正确地将手续费应用于每个商品的价格?

2. 累加总金额的:是否正确地累加了每个商品的价格?

3. 异常处理:是否正确处理了不支持的支付?

我们逐步检查每个可能的BUG点。

检查信用卡支付手续费的计算

在`calculate_total`方法中,手续费是通过代码计算的:

python

total = sum(price * 1.1 for item, price in self.items)

这段代码看起来是正确的,它将每个商品的价格乘以1.1,即增加了10%的手续费。我们可以暂时排除手续费计算的BUG。

检查累加总金额的

在信用卡支付的情况下,我们期望的总金额应该是商品价格加上10%的手续费。根据题目计算出的总金额比预期多了110元。这意味着每个商品的手续费被多计算了一次。

为了验证这一点,我们可以尝试将信用卡支付的手续费累加逻辑单独提出来,并检查其正确性:

python

def calculate_credit_fee(self, price):

return price * 0.1

# 测试信用卡手续费计算

print(cart.calculate_credit_fee(1000)) # 应输出100

print(cart.calculate_credit_fee(50)) # 应输出5

通过上述测试,我们可以看到信用卡支付的手续费计算是正确的。我们可以排除累加总金额的BUG。

检查异常处理

我们检查了不支持的支付的情况。在代码中,支付不是'credit'或'cash',会抛出一个`ValueError`异常。这部分代码看起来是正确的,没有明显的BUG。

定位BUG并修复

经过上述分析,我们可以得出BUG出信用卡支付手续费的计算上。我们只需要在计算总金额时,对每个商品的价格加上一次手续费即可。是修复后的代码:

python

class ShoppingCart:

def __init__(self):

self.items = []

def add_item(self, item, price):

self.items.append((item, price))

def calculate_total(self, payment_method):

total = 0

for item, price in self.items:

if payment_method == 'credit':

total += price * 1.1 # 只对信用卡支付的商品加10%的手续费

else:

total += price

return total

# 测试代码

cart = ShoppingCart()

cart.add_item("Laptop", 1000)

cart.add_item("Mouse", 50)

print(cart.calculate_total('credit')) # 应输出1110

print(cart.calculate_total('cash')) # 应输出1050

通过这样的修复,我们解决了BUG,确保了在信用卡支付时,每个商品的手续费只计算一次。

发表评论
暂无评论

还没有评论呢,快来抢沙发~