简单的For循环和if语句

时间:2016-02-13 16:31:56

标签: c# if-statement for-loop incremental-build

我要做的是将提款金额限制为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);
    }
}

1 个答案:

答案 0 :(得分: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);
}

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

旁注,如果您不需要双倍值,则可以使用remainder operator将整个代码缩减为几行。例如

int WithdrawalAmount = 120;
if ((WithdrawalAmount % 20) == 0)
   ... good ...
else
   ... bad ...