-4

我想做的是将提款金额限制为 20 美元,最高可达 500 美元。我知道我在这里缺少一些简单的元素来做到这一点。我的代码一直有效,直到我尝试以 20 为增量。

double AccountBalance = 1500;
double WithdrawalAmount;
WithdrawalAmount = double.Parse(textInput.Text);
Double MaxWithdrawalAmount = 0;
for (MaxWithdrawalAmount = 0; MaxWithdrawalAmount <= 500; MaxWithdrawalAmount += 20)
{ 
    if (WithdrawalAmount == MaxWithdrawalAmount)
    {
        double Total = (AccountBalance - WithdrawalAmount);
        textTotal.Text = ("Total amount" + Convert.ToString(Total));
    }
    else
    {
        textError.Text = ("Only Increments of $20 allowed for withdraw up to $100");
        textTotal.Text = ("" + AccountBalance);
    }
}
4

1 回答 1

2

你应该以不同的方式处理你的循环

bool ok = false;
for (MaxWithdrawalAmount = 0; MaxWithdrawalAmount <= 500; MaxWithdrawalAmount += 20)
{
    if (WithdrawalAmount == MaxWithdrawalAmount)
    {
        double Total = (AccountBalance - WithdrawalAmount);
        textTotal.Text = "Total amount" + Convert.ToString(Total);
        ok = true;
        break;
    }
}
if (!ok)
{
    textError.Text = ("Only Increments of $20 allowed for withdraw up to $100");
    textTotal.Text = ("" + AccountBalance);
}

我已将错误消息移到循环之外。如果在循环内我找到了正确的退出值,那么我停止循环并设置一个标志以避免最终的错误消息

旁注,如果您不需要双精度值,则可以使用余数运算符将整个代码减少到几行。例如

int WithdrawalAmount = 120;
if ((WithdrawalAmount % 20) == 0)
   ... good ...
else
   ... bad ...
于 2016-02-13T16:39:17.390 回答