I am a C++ programmer trying to get a grasp of the C language syntax and I do not understand why I'm getting garbage values when I use pointers in this function.
#include<stdio.h>
#include <math.h>
void separate(double, double *dollar, double *quarter, double *dime, double *nickle, double *penny);
int
main(void)
{
double amount = 38.39, change, paid = 40.0, dollar, quarter, dime, nickle, penny;
change = paid - amount;
separate(change, &dollar, &quarter, &dime, &nickle, &penny);
printf("Your total change is: $%d\n", change);
printf("Dollars: %d\n", dollar);
printf("Quarters: %d\n", quarter);
printf("Dimes: %d\n", dime);
printf("Nickles: %d\n", nickle);
printf("Pennies: %d\n", penny);
getchar();
return (0);
}
void separate(double change, double *dollar, double *quarter, double *dime, double *nickle, double *penny)
{
double coins;
coins = change - floor(change);
*dollar = floor(change);
*quarter = coins / 25;
coins = coins - (*quarter * 25);
*dime = coins / 10;
coins = coins - (*dime * 10);
*nickle = coins / 5;
*penny = coins - (*nickle * 5);
}
I suspect that your problem is that you're not doing division correctly.
Take a look:
void separate(double change, double *dollar, double *quarter, double *dime, double *nickle, double *penny)
{
// for your example, change is initially 1.61
double coins;
coins = change - floor(change); // .61
*dollar = floor(change); // 1
*quarter = coins / 25; // .0244
coins = coins - (*quarter * 25); // 0
*dime = coins / 10; // 0
coins = coins - (*dime * 10); // 0
*nickle = coins / 5; // 0
*penny = coins - (*nickle * 5); // 0
}
Integer division and floating point division don't work the same way. You should instead multiply by 100 to get the number of cents, divide by 25 to get the number of quarters, then floor to make it a whole number.
*quarters = floor(coins * (100 / 25)); // floor(2.44) = 2
coins = coins - *quarters * 25; // .11
Repeat as needed to get quantities of other coins.
Also, everyone else has mentioned that you're using %d
to print doubles instead of %f
(%d
is an integer format string) so I'll mention it too, because it's part of the problem.