我要编写一个函数来从包含初始余额的数组中提取资金。
如果余额不足,则会显示警告消息以及用户的余额。
提示用户再次输入新的金额,如果金额还可以,则提款操作已完成并且余额已更新并显示菜单。
如果余额仍然不足,将终止提款操作并显示菜单。
以下是我第一次尝试输入低于余额的金额时有效的代码。但是,如果我在第二次尝试中输入有效金额,就不能很好地更新余额。
double withdrawAmount(int pin, double balance[]){
double amount;
double newBalance = balance[pin];
int withdrawTrial = 0;
do{
system("cls");
cout << "-----------------------------------------" << endl;
cout << "\tWELCOME TO EDON ATM" << endl;
cout << "-----------------------------------------" << endl;
cout << endl;
cout << "Please enter amount to be withdrawn: $";
cin >> amount;
if (balance[pin] < amount){
cout << endl;
cout << "Insufficient Balance!" << endl;
cout << "Your balance is: $" << balance[pin] << endl;
cout << endl;
while (withdrawTrial < 1){
withdrawTrial++;
cout << "Please enter amount to be withdrawn: $";
cin >> amount;
}
if (withdrawTrial == 1){
menuBoard();
return newBalance;
}
}
balance[pin] -= amount;
newBalance = balance[pin];
} while (amount < 0);
return newBalance;
}
答案 0 :(得分:0)
您没有正确按照说明进行操作。您没有在第二个提示上验证用户的输入。完全摆脱while (withdrawTrial < 1)
循环。提示一次并验证。如果amount
大于可用的balance
,则再次提示并重新验证。如果amount
仍然大于可用的balance
,则退出。不需要循环(除非您要验证用户是否实际上输入了浮点数,否则就没有其他要求了。)
此外,您不应该在menuBoard()
本身内部调用withdrawAmount()
,而应该在withdrawAmount()
退出之后调用它。
double inputDollars(const char *prompt){
double value;
do {
cout << prompt << ": $";
if (cin >> value)
break;
cout << endl;
cout << "Invalid Input!" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (true);
return value;
}
double withdrawAmount(int pin, double balance[]){
double amount;
system("cls");
cout << "-----------------------------------------" << endl;
cout << "\tWELCOME TO EDON ATM" << endl;
cout << "-----------------------------------------" << endl;
cout << endl;
amount = inputDollars("Please enter amount to be withdrawn");
if (balance[pin] < amount){
cout << endl;
cout << "Insufficient Balance!" << endl;
cout << "Your balance is: $" << balance[pin] << endl;
cout << endl;
amount = inputDollars("Please enter amount to be withdrawn");
if (balance[pin] < amount){
cout << endl;
cout << "Insufficient Balance!" << endl;
return balance[pin];
}
}
balance[pin] -= amount;
return balance[pin];
}
...
double balances[N];
int pin;
...
withdrawAmount(pin, balances);
menuBoard();