我在查找和解决基本ATM程序中的错误时遇到了困难。这个问题体现在支票账户和储蓄账户的取款选项上。当账户的可用资金为零时,它将允许用户输入一个负数,这实际上是透支了账户。我正在努力防止这种情况发生。
此外,如果没有可提取的资金,程序继续循环,从而不允许用户利用菜单选择不同的选项。
我提供了屏幕输出的示例,说明了问题和一些源代码。
问题
问题#include <iomanip>
#include <iostream>
using std::cin;
using std::cout;
double checking_balance = 2500.00, savings_balance = 1000.00, savings_amount,
checking_amount;
int menu;
int main() {
do {
// Main Menu
cout << std::fixed << std::setprecision(2);
cout << "n";
cout << "tWelcome to Seabreeze Bankn";
cout << "*********************************nn";
cout << "1. Savings Accountn";
cout << "2. Checking Accountn";
cout << "3. Quitnn";
cin >> menu;
cout << "nn";
// User validation for the Main Menu
if (menu < 1 || menu > 3) {
cout << "You have entered an invalid option.n";
cout << "Please enter a number 1-3 > ";
cin >> menu;
cout << "nn";
}
switch (menu) {
case 1:
int savings_menu;
do {
// Savings Account Menu
cout << "ttSavings Accountnn";
cout << "Please enter a menu item (1-3) >n";
cout << "*********************************n";
cout << "1. Withdrawaln";
cout << "2. Depositn";
cout << "3. Main Menun";
cout << "nn";
cin >> savings_menu;
cout << "n";
// Withdrawal selection for Savings Account
if (savings_menu == 1) {
cout << "How much would you like to withdraw from your savings "
"account: ";
cin >> savings_amount;
cout << "n";
while (savings_balance < savings_amount) {
cout << "You do not have enough funds in your account to withdraw "
"that muchn";
cout << "Please enter a smaller amount: ";
cin >> savings_amount;
cout << "n";
}
while (savings_amount <= 0) {
cout << "Please enter an amount greater than 0: ";
cin >> savings_amount;
}
savings_balance -= savings_amount;
cout << "Your Savings Account Balance: " << savings_balance << "nn";
if (savings_balance == 0) {
cout << "You now have zero funds in your Savings Account.nn";
}
}
这是一个浮点算术问题。
通常,由于舍入误差,浮点运算不精确,saving_amount不等于0,但它几乎等于0。
我更喜欢强制转换选项,因为在某些情况下,如果结果为负,使用round()函数将需要更多的修改。
代替"while (savings_amount <= 0)"你应该使用while (int(saving_amount) <= 0).同样,当你在程序中使用条件运算符时,你必须进行类型转换。
为防止输入负数提取,必须加上&;if&;语句检查number是否为负数。