•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the C section within the Software Development category of DaniWeb, a massive community of 397,765 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,498 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C advertiser:
Break down an amount into units of dollars and cents.
#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, */
Post Comment
•
•
•
•
DaniWeb Marketplace (Sponsored Links)