所以,我遇到了使用float的問題。當我去編譯時,有一些特定的區域會告訴我一個錯誤:「不能顯式地將類型'double'轉換爲'float'。存在明確的轉換(你是否錯過了一隻貓?)問題是它只是在做它的三行代碼(涉及remainingChange%0.25,remainingChange%0.10和remainingChange%0.05)我假設這與小數和精度有關,但我似乎無法弄清楚。解決它的任何指向我的方向是正確的建議,將不勝感激謝謝Float的問題
這裏是適用的代碼:
private void button1_Click(object sender, RoutedEventArgs e)
{
//Set up try catch for errors
try
{
//declare variables
float changeDue = 0;
float remainingChange = 0;
float purchaseAmount = 0;
float paymentAmount = 0;
//if statement to verify that the purchase amount is not empty
if (string.IsNullOrWhiteSpace(PurchaseAmount.Text))
{
Error.Text = "The purhcase amount is empty";
return;
}
//else-if statement to verify that the payment amount is not empty
else if (string.IsNullOrWhiteSpace(PaymentAmount.Text))
{
Error.Text = "The submitted amount is empty";
return;
}
//else-if statement to verify that the purchase and payment amounts are numeric
else if (!float.TryParse(PurchaseAmount.Text, out purchaseAmount))
{
Error.Text = "The purchase amount will only take numbers";
return;
}
else if (!float.TryParse(PaymentAmount.Text, out paymentAmount))
{
Error.Text = "The submitted amount can only accept numbers";
return;
}
//else-if statement to verify that the payment amount is greater than the purhcase amount
else if (purchaseAmount > paymentAmount)
{
Error.Text = "Submitted value can't be less than purchased value";
return;
}
Error.Text = "";
//Determine the change due and how it will be paid out, then write the values to the window
changeDue = paymentAmount - purchaseAmount;
remainingChange = changeDue % 100;
Hundreds.Text = ((changeDue/100) - (remainingChange/100)).ToString();
Fifties.Text = ((remainingChange/50) - ((remainingChange % 50)/50)).ToString();
remainingChange = remainingChange % 50;
Twenties.Text = ((remainingChange/20) - ((remainingChange % 20)/20)).ToString();
remainingChange = remainingChange % 20;
Tens.Text = ((remainingChange/10) - ((remainingChange % 10)/10)).ToString();
remainingChange = remainingChange % 10;
Fives.Text = ((remainingChange/5) - ((remainingChange % 5)/5)).ToString();
remainingChange = remainingChange % 5;
Ones.Text = ((remainingChange/1) - ((remainingChange % 1)/1)).ToString();
remainingChange = remainingChange % 1;
Quarters.Text = ((remainingChange/0.25) - ((remainingChange % 0.25)/0.25)).ToString();
remainingChange = remainingChange % 0.25;
Dimes.Text = ((remainingChange/0.10) - ((remainingChange % 0.10)/0.10)).ToString();
remainingChange = remainingChange % 0.10;
Nickels.Text = ((remainingChange/0.05) - ((remainingChange % 0.05)/0.05)).ToString();
remainingChange = remainingChange % 0.05;
Pennies.Text = ((remainingChange/0.01) - ((remainingChange % 0.01)/0.01)).ToString();
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred. The error was: " + ex.Message, "Error sample", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
這似乎解決了這個問題。我感謝您的幫助。 – MatthewSpire