C++取款功能实现及美元美分归一化问题求助
Hey there! Let's work through that withdrawal function hurdle you're facing. It's awesome you've got the rest of your SavingsAccount functionality up and running—nice work getting this far.
The core issue here is preventing your total cent balance from going negative, which boils down to validating sufficient funds before you subtract the withdrawal amount, plus sticking to the same cent-based arithmetic you used for deposits.
First, let's recap the key formula logic you should use (building on your deposit code's approach of handling everything in total cents to avoid floating point errors):
Key Formulas & Logic Steps
- Convert withdrawal input to total cents:
Just like you convert deposit amounts, turn the user's dollar + cent input into a single integer of total cents:int withdrawTotal = dollarHold * 100 + centHold; - Check for sufficient funds:
Before making any changes, verify your account's stored total cents balance is at least the withdrawal amount. This is the critical step to prevent negative balances:if (withdrawTotal > totalCents) { // Assume `totalCents` is your account's stored balance in cents cout << "Error: Insufficient funds for this withdrawal." << endl; return; // Exit the function without modifying balance } - Execute the withdrawal:
If funds are sufficient, subtract the total withdrawal cents from your account's total cents:totalCents -= withdrawTotal; - (Optional) Convert back to dollars & cents for display:
If you need to show the updated balance, reverse the conversion:
Useint newDollars = totalCents / 100; int newCents = totalCents % 100;setw(2)andsetfill('0')from<iomanip>to ensure single-digit cents display as two digits (e.g., $5.03 instead of $5.3).
Full Withdrawal Function Example
Here's how this all comes together in code, matching your deposit function's style:
#include <iostream> #include <iomanip> // For setw/setfill void SavingsAccount::withdraw() { int dollarHold, centHold; cout << "Please input the dollars to be withdrawn: "; cin >> dollarHold; cout << "Please input the cents to be withdrawn: "; cin >> centHold; // Convert withdrawal amount to total cents (handles cent values over 99 automatically!) int withdrawTotal = dollarHold * 100 + centHold; // Validate sufficient funds first if (withdrawTotal > totalCents) { cout << "Sorry, you don't have enough funds for this withdrawal." << endl; return; } // Perform the withdrawal totalCents -= withdrawTotal; // Show updated balance with proper formatting int newDollars = totalCents / 100; int newCents = totalCents % 100; cout << "Withdrawal successful! Your new balance is: $" << newDollars << "." << setw(2) << setfill('0') << newCents << endl; }
A quick note: This approach works even if the user enters more than 99 cents for the withdrawal (e.g., $2 and 150 cents gets converted to 350 total cents automatically), just like your deposit logic handles excess cents.
内容的提问来源于stack exchange,提问作者Sneaky Kitty Gaming

