1

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);
}

output

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.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64

2 Answers2

2

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

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
2

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);
Nathan C
  • 205
  • 2
  • 10