Reputation: 23
I was trying to create a program that will display the imputed amount and the number of $10 and $1 notes that an ATM can dispense but it will not display correct amount of $1 notes.
int amount = int.Parse(txtAmount.Text);
int tenNotes=0, oneNotes=0;
CalculateNotes(amount, ref tenNotes, ref oneNotes);
private void CalculateNotes( int amount, ref int tenNotes, ref int OneNotes)
{
tenNotes = amount /10;
OneNotes = amount - amount % 10;
rtbDisplay.AppendText("Ammount is " + amount + "Ten notes is" + tenNotes + "One notes is" + OneNotes);
}
This is the output I have tried different method of calculation for $1 notes but it does not work. Am I supposed to use out instead of ref or is there an error in my calculation? Thank you for any help.
Upvotes: 1
Views: 512
Reputation: 205
An alternate to the solution that Steve gave, you could also do the following:
Change:
OneNotes = amount - amount % 10;
to:
OneNotes = amount % 10;
Additional Alternate - It should be noted that what you are trying to do is already a pre-existing function in the System.Math library. As such, you can replace the following code block:
tenNotes = amount /10;
OneNotes = amount - amount % 10;
with:
tenNotes = Math.DivRem(amount, 10, out OneNotes);
Upvotes: 2
Reputation: 216313
You should change this line
OneNotes = amount - amount % 10;
to this one
OneNotes = amount - (tenNotes * 10);
and please reconsider your using of int.Parse to read the input from the textbox. If your user types an invalid integer value you get an exception. This exception could be easily avoided using Int32.TryParse
Finally, I suggest also to use the out keyword for your parameters instead of ref.
See When to use ref vs out
Upvotes: 2