为家庭作业制定一个找零程序,当输入金额时,它必须返回找零金额(它基于澳大利亚货币),我已经将其工作到了五十美分。当计算零钱并且程序必须返回二十美分、十美分或五美分零钱的值时,程序会冻结
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
double change = Convert.ToDouble(txtOffered.Text) - Convert.ToDouble(txtDue.Text);
// MessageBox.Show(change.ToString());
double hund = 100;
double fifty = 50;
double twent = 20;
double ten = 10;
double five = 5;
double two = 2;
double one = 1;
double fifcent = 0.50;
double twentcent = 0.20;
double tencent = 0.10;
double fivecent = 0.05;
while (change > 0)
{
if (change >= hund)
{
txtChange.Text += "1x $100 \r\n";
change = change - hund;
}
else if (change >= fifty)
{
txtChange.Text += "1x $50 \r\n";
change = change - fifty;
}
if (change >= twent)
{
txtChange.Text += "1x $20 \r\n";
change = change - twent;
}
else if (change >= ten)
{
txtChange.Text += "1x $10 \r\n";
change = change - ten;
}
if (change >= five)
{
txtChange.Text += "1x $5 \r\n";
change = change - five;
}
else if (change >= two)
{
txtChange.Text += "1x $2 \r\n";
change = change - two;
}
if (change >= one)
{
txtChange.Text += "1x $1 \r\n";
change = change - one;
}
else if (change >= fifcent)
{
txtChange.Text += "1x 50c \r\n";
change = change - fifcent;
}
if (change >= twentcent)
{
txtChange.Text += "1x 20c \r\n";
change = change - twentcent;
}
else if (change >= tencent)
{
txtChange.Text += "1x 10c \r\n";
change = change - tencent;
}
if (change >= fivecent)
{
txtChange.Text += "1x 5c \r\n";
change = change - fivecent;
}
}
}
}
如果您输入金额,应用程序将卡住< 0.05 or you receive amount < 0.05 after change result.
原因在这里:如果您的更改变量值 > 0,但是 < 0.05 you'll stuck forever.
while (change > 0)
{
...
if (change >= fivecent)
{
txtChange.Text += "1x 5c \r\n";
change = change - fivecent;
}
}
对于新手来说,这可能很难发现。您的代码的问题是您使用了错误的数据类型。您应该使用
double
而不是 decimal
:
decimal change = Convert.ToDouble(txtOffered.Text) - Convert.ToDouble(txtDue.Text);
// MessageBox.Show(change.ToString());
decimal hund = 100;
decimal fifty = 50;
decimal twent = 20;
decimal ten = 10;
decimal five = 5;
decimal two = 2;
decimal one = 1;
decimal fifcent = 0.50m;
decimal twentcent = 0.20m;
decimal tencent = 0.10m;
decimal fivecent = 0.05m;
有了这个,你的代码就不会冻结。
对此进行解释,问题是,使用
double
0.25 - 0.20
的结果是...0.049999999999999989
。这是因为 double 使用浮点值,这可能会导致舍入问题。如果您想了解更多有关浮点计算的信息,请查看此处。