Break down an amount into units of dollars and cents.
Currency: Making Change
#include <stdio.h>
void breakdown(double amount)
{
size_t i;
struct currency
{
int cents;
const char *name;
} Unit[] =
{
{ 10000, "hundreds" },
{ 5000, "fifties" },
{ 2000, "twenties" },
{ 1000, "tens" },
{ 500, "fives" },
{ 100, "ones" },
{ 25, "quarters" },
{ 10, "dimes" },
{ 5, "nickels" },
{ 1, "pennies" },
};
int cents = amount * 100 + 0.5; /* add 0.5 to round */
printf("$%.2f : ", amount);
for ( i = 0; i < sizeof Unit / sizeof *Unit; ++i )
{
int count = cents / Unit[i].cents;
if ( count )
{
printf("%d %s, ", count, Unit[i].name);
}
cents %= Unit[i].cents;
}
putchar('\n');
}
int main()
{
double cost = 20.21, tendered = 50.00, change = tendered - cost;
breakdown(cost);
breakdown(tendered);
breakdown(change);
return 0;
}
/* my output
$20.21 : 1 twenties, 2 dimes, 1 pennies,
$50.00 : 1 fifties,
$29.79 : 1 twenties, 1 fives, 4 ones, 3 quarters, 4 pennies,
*/
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.