Xcode开发:BillSplitter应用金额计算错误问题求助
Fixing BillSplitter Calculation Errors in Xcode
Hey there! Let's get your BillSplitter app calculating correctly—those off totals are easy to fix once we spot the two key mistakes in your calculation logic.
What's Causing the Wrong Numbers?
Let's break down the issues with your current code:
- Incorrect Grand Total Calculation: Right now, you're adding the raw tip percentage value (like 10) directly to the meal total (60), which gives 70 instead of the correct 66. You need to calculate the actual tip amount first (10% of 60 is 6) and add that to the meal total.
- Incorrect Per-Person Calculation: You're only dividing the meal total by the number of diners, not the grand total that includes the tip. That's why you're getting 30 instead of 33 per person.
Corrected Code for the calculate Method
Here's the fixed version of your calculate function— I've updated the key calculation lines and kept your formatting logic intact:
@IBAction func calculate(_ sender: Any) { if let dinerStr = dinersTextField.text, let tipStr = tipTextField.text, let totalStr = totalCostTextField.text, let diner = Double(dinerStr), let tip = Double(tipStr), let total = Double(totalStr) { // Calculate actual tip amount and grand total first let tipAmount = (total * tip) / 100 let grandTotal = total + tipAmount // Format all values for display let formattedDiners = String(format: "%.0f", diner) let formattedCost = String(format: "%.2f", total) let formattedTip = String(format: "%.2f", tipAmount) let formattedGTotal = String(format: "%.2f", grandTotal) let formattedDinerPays = String(format: "%.2f", grandTotal / diner) resultTextLabel.text = "The number of diners: \(formattedDiners)\nAmount of Tip: $\(formattedTip)\nAmount of bill: $\(formattedCost)\nGrand Total: $\(formattedGTotal)\nEach diner pays: $\(formattedDinerPays)" } }
Let's Test It Out
With your input (2 diners, $60 total, 10% tip):
- Tip amount becomes
(60 * 10)/100 = 6 - Grand total is
60 + 6 = 66 - Per-person cost is
66 / 2 = 33
Perfect—those are the correct numbers you were expecting!
内容的提问来源于stack exchange,提问作者nedandkay
相关产品推荐
相关产品推荐

