Link to home
Start Free TrialLog in
Avatar of accesspoint
accesspoint

asked on

Need help using modular division in C++

My school assignment requires me to write a program to find out the change left after you input the amount tendered. my teacher tells us to use the % syntax which returns the remainder after division. i tried that but it gives me a error about using %with type double variables. but i must have it type double because i need to find the change in cents and double is the only variable that supports decimals. i have just started learning c++ so please help. thanks.
Avatar of nagraves
nagraves

% or 'mod' is used with integer division.

int x = 9;
iny y = 5;
int z = 0;

z = x%y;

z is now equal to 4.  the modulus gives you the remainder.
To add to my comment earlier, you could first multiply your double or float by 100 and then typecast to int. then use %.

None the less, % is an integer operator and cannot be used with floating point numbers.
>>>> i must have it type double because i need to find the change in cents

No, the number of cents is an integer and not a double:

    double priceInDollars = 11.27;  // dollars
    int       priceInCents   = (int) (price*100);

    int dollar  = priceInCents/ 100;         // integer division gives the right number
    priceInCents = (priceInCents%100);  // calculate remainder
    int quarter    = priceInCents / 25;      // and so on ...
    ...

Regards, Alex


Correction:

   int       priceInCents   = (int) (priceInDollars*100);
Thank you itsmeandnobodyelse. You have demonstrated what I wrote quite well. I didn't think to give an example of typecasting for the kid. :)
Avatar of accesspoint

ASKER

ok so if im understanding correctly, i first have to typecast to int before i can use the mod division and then divide by 100 to get back the decimal?
ASKER CERTIFIED SOLUTION
Avatar of nagraves
nagraves

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>>> then divide by 100 to get back the decimal?

No, the results you need - as nagraves told you - are integers. The numbers of dollars, quarters, nickels, cents, all are integers. Actually, you don't need any typecasting if you calculate the number of cents like that:

    double d = 12.27;
    int       c = 100 * d; // 1227

>>>> int changeDollars = changeInCents/100;

What you see here is an integer division, i. e. the result is an integer - not a decimal -  and that is good as we need the number of dollar bills here and not the decimal value of the change.

Regards, Alex

Well, I'd like the points :)
sorry guys that i took so long to respond. i didn't even realize i had a open question until i got the email!

anyways, i tried what nagraves did and it worked out fine. thanks guys.