JoshM
JoshM

Reputation: 33

Penny calculator mod division

I have an assignment for a beginners VB class, and I have looked for examples for a penny calculator and have read them and tried to figure out where I am going wrong. I have a text box that takes the number of pennies you want to figure out. If you input 101 pennies it comes back with 1 dollar and 1 penny.

Strangely it works for up to 137 pennies. That comes back with 1 dollar 1 quarter 1 dime 2 pennies. If it goes to 138 or higher it just screws up. If I input 138 I get 1 dollar, 2 quarters, 1 dime, 1 nickel, 3 pennies. If I use 17 I get 1 quarter, 2 dimes, 1 nickel, 2 pennies.

Here is the arithmetic portion of my code.

    DolBack = intLeftOver / 100
    intLeftOver = intLeftOver Mod 100
    LblDolRes.Text = DolBack.ToString

    QrtBack = intLeftOver / 25
    intLeftOver = intLeftOver Mod 25
    LblQrtRes.Text = QrtBack.ToString

    DimBack = intLeftOver / 10
    intLeftOver = intLeftOver Mod 10
    LblDimRes.Text = DimBack.ToString

    NicBack = intLeftOver / 5
    intLeftOver = intLeftOver Mod 5
    LblNicRes.Text = NicBack.ToString

    PenBack = intLeftOver
    LblPenRes.Text = PenBack.ToString

I have tried to look my code over and look at other examples, but apparently I'm doing it a little differently. If anyone could point out the apparent major flaw in my code or my way of doing it I would appreciate it.

Further clarifying I have looked at the post at Penny Calculator Obviously there are a few differences with the actual arithmetic. In the link given is that because that is the only way to do it without rounding issues?

there are 100 pennies in a dollar, 25 pennies in a quarter, 10 pennies in a dime, 5 pennies in a nickel.

EDIT: Thanks for the help and pointing out my error. It's appreciated.

Upvotes: 3

Views: 925

Answers (2)

dbasnett
dbasnett

Reputation: 11773

The Math.DivRem method is helpful for this kind of problem.

    Dim dollars As Integer
    Dim fifty As Integer
    Dim quarter As Integer
    Dim dime As Integer
    Dim nickel As Integer
    Dim pennies As Integer = 137

    dollars = Math.DivRem(pennies, 100, pennies)
    fifty = Math.DivRem(pennies, 50, pennies)
    quarter = Math.DivRem(pennies, 25, pennies)
    dime = Math.DivRem(pennies, 10, pennies)
    nickel = Math.DivRem(pennies, 5, pennies)

Upvotes: 1

ClickRick
ClickRick

Reputation: 1568

You're right that it's a rounding error. Use

DolBack = intLeftOver \ 100

instead of

DolBack = intLeftOver / 100

(and the same for the other ones) and you'll see a very different result.

The reason is that the / operator will do floating point division, regardless of the values either side of it, so 38/25 will yield an answer of 1.52, which rounds upwards (as you suspected) when assigned back to the variable, which is defined as an Integer. On the other hand, the \ operator will do integer division, truncating rather than rounding.

Upvotes: 1

Related Questions