Thread: Program to calculate change return.

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    49

    Program to calculate change return.

    Hi guys, i'm new here and i figured what better place to be asking C question than a place dedicated to it... i'm not a total n00b, i just can't write code at like i write english, but i can fluently understand it, i've done and still do programming in many languages and after i decided to go back to university and having to retake C (something i did yrs ago B4 i dropped out) i'm feeling a little rusty and kinda outta shape, reading the class notes obviously helps but u know when u know more and it's not that that's stopping you... anyhow a little FYI about me just so i don't automatically get blasted into smithereens. and before i state my issue i'd like to say thanks to whoever takes the time to read this and hopefully i might get some insight.
    so here's the deal...
    an amount of change (money to be returned on purchase) is to be inputted by the user, between 0, inclusive and 5 non-inclusive (0<=change<5)
    on enter, the program prints out, your change is composed of toonies (yes canadian money :P), loonies, quarters... etc pennies.
    Now that's simple, it's been done and i'm getting good answers... but also bad ones...
    say for example i put in 4.99 for change... my change is missing a penny... and only for some numbers am i getting a -1 on the pennies...

    i'll explain my code before i paste it too, if the comments lack.
    i decided to go with the "multiply by 100" to get an all pennies amount and worked my way down with while loops through 200/100/25/10/5/1 cents
    these while loops were basically counting my coins and subtracting the amounts from the total cents.
    another way would definitely be with mod(&#37 i'm not sure which is short/faster

    here's the code:
    Code:
    /*
    #include <stdio.h>
    
    main ()
    
    {   // initialisation des variables
    
       float monnaie;                            // Nombre entr&#233; par usager
       int cents=0;                                // variable utilis&#233;e pour les calculs
       int validation;
       char condition;
       // Boucle do ... while, pour ne pas devoir repartir le programme pour chaque calcul
       do
         {
            int toonies=0;
            int loonies=0;
            int quarters=0;
            int dimes=0;
            int nickels=0;
            int pennies=0;
            // Nbr de pi&#232;ces
    
       do              // boucle de validation (monnaie entre 0 inclus et 5 non inclus)
         {
            printf("Entrez le montant a remettre: (x.xx)");     // Entr&#233;e du change a remettre
            fflush(stdin);                                      // vider la memoire temp.
            scanf("%f", monnaie);
    
            validation = ( monnaie >= 0 && monnaie < 5);
    
            if (!validation)   // si pas vrai
            printf ("Montant de change non valide! SVP le retaper. \n");
          
    	  } while (!validation);       // tant que non valide
    
          // Calculs
          		cents = monnaie * 100;		// pour faciliter les calculs
    			while (cents >= 200) {
    				toonies++;
    				cents -= 200;
    			}
    			while (cents >= 100) {
    				loonies++;
    				cents -= 100;
    			}
    			while (cents >= 25) {
    				quarters++;
    				cents -= 25;
    			}
    			while (cents >= 10) {
    				dimes++;
    				cents -= 10;
    			}
    			while (cents >= 5) {
    				nickels++;
    				cents -= 5;
    			}
                while (cents >=1) {
                    cents++;
                    cents-=1;
                    } 
          // Affichage des resultats
    		printf ("Vous aurez: \n");
            printf ("%d pieces de 2$, \n", toonies);
            printf ("%d pieces de 1$, \n", loonies);
            printf ("%d pieces de 25c, \n", quarters);
            printf ("%d pieces de 10c, \n", dimes);
            printf ("%d pieces de 5c \n", nickels);
            printf ("et \n%d pieces de 1c", pennies);
    
          // Condition requise pour repartir du d&#233;but
            printf ("\nVoulez vous faire un autre calcul, (o/n)?");
            fflush (stdin);                        // Fonction pour vider stdin
            condition = toupper(getchar());        // Capitaliser la letter et soumettre &#224; condition
          
    	  } while ( condition == 'O');             // Repartir du d&#233;but si O
    
    
       system("pause") ;
    }
    
    
    /*
    
    R&#233;sultats:
    ==========
    
    
    
    */
    Again, thanks... this is greatly appreciated.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    (Cautionary note: I did not run the code.) It appears that you are assuming that 4.99*100 = 499. This is not true. (It all comes down to 4.99 not being representable in binary format in finite space, so your computer uses an approximation, but when you multiply by 100 and then truncate (which is what assigning to an int does), that approximation comes back to bite you.) I would bet that if you print cents before starting, you'd see that in your problem cases it's one less than you want. So: maybe something like monnaie * 100 + 0.5 will help with that.

    (I don't see how you could get the pennies right -- you never change the value of that variable in your code anywhere.)

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    i just realized that just before i refreshed the page

    i believe my scanf should be in the form &#37;f1.2 to grab 1 number before the decimal and 2 after
    edit: this would force the capture of the x.xx amount and nothing after, right ?

    the problem i'm having right now is the compiling goes fine but the program is crashing... in fact any program i made in the last couple days won't run anymore... using Dev-C++
    Last edited by OrAnGeWorX; 11-17-2008 at 03:08 AM.

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    &#37;1.2f would not get what you want, no. There is no . in scanf formats. And it wouldn't matter, because 4.99 is quite simply not storable in floating-point format.[1] You also need an & in front of the variable in scanf, as well. To restate: the input is great (modulo the & in front of the variable). The calculation using it is broken.

    [1]By any non-BCD floating-point format, but I'm not aware of any system that gives you BCD by default.
    Last edited by tabstop; 11-17-2008 at 03:18 AM.

  5. #5
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    thanks for the help tabstop.. you're right the 1.2 didn't change anything
    but what's weird is that at 4.90 to 4.98... the numbers are correct.... 4.99 1 penny less... and a few other numbers as well...

    edit:
    would u suggest i split the change in dollars and cents and then work with modulo ?
    Last edited by OrAnGeWorX; 11-17-2008 at 03:38 AM.

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So this page will tell you what number is actually stored when you type in a given number. You can see that, when you type in 4.99, your float variable actually contains 4.9899998 (it's the best you can do with only 32 bits). Multiplying that by a 100 will give you 498.99998, and then the automatic truncation kicks in and you get 498. This is why you need to add that 0.5 (or do some other rounding) to get the value you want.

  7. #7
    Why bbebfe is not bbebfe? bbebfe's Avatar
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    27
    There are two problems within your code.
    1. You should pass a pointer rather than the variable itself to scanf
    Code:
    scanf("&#37;f", &monnaie);
    2. Adding #include <stdlib.h> in your code in which system function is declared.

  8. #8
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    i'm understanding the truncating part but say 4.99 wasn't 4.99 but more 4.99xxxxx
    if it were to truncate... why would it at 498 when multiplied by 100 rather than 500 ?
    just thought that occurred to me

  9. #9
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    Quote Originally Posted by bbebfe View Post
    There are two problems within your code.
    1. You should pass a pointer rather than the variable itself to scanf
    Code:
    scanf("%f", &monnaie);
    I had corrected that... was working on 2 of the same file at the same time and pasted the one last modified. my bad

    2. Adding #include <stdlib.h> in your code in which system function is declared.
    which system function is that? the toInt() ?
    because even with stdlib included it's not working... odd it worked like an hour ago... only thing that change is PC location... school to home lol

  10. #10
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    i just read some where that it's better to use long instead of int and try to convert a real into an in... as the cents is an int but it's being give the value of amount (real) * 100

    just tried the code but still... 4.99 gives back 4.98 in change.. greedy pc b@stard.. 4.66 gives 4.65 too..

  11. #11
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    ok problem resolved... tabstop all it needed was that 0.5 you mentioned in your first post...
    feel silly
    thanks so much for the help... i can't believe i almost got a hernia from this.... been on it 12 hours straight!

  12. #12
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by OrAnGeWorX View Post
    i'm understanding the truncating part but say 4.99 wasn't 4.99 but more 4.99xxxxx
    if it were to truncate... why would it at 498 when multiplied by 100 rather than 500 ?
    just thought that occurred to me
    Truncate means to get rid of the extra decimal, instead of trying to round it off. Since multiplying gives you 498.99998, truncating leaves 498 instead of 499.

  13. #13
    Registered User
    Join Date
    Nov 2008
    Posts
    49
    Quote Originally Posted by tabstop View Post
    Truncate means to get rid of the extra decimal, instead of trying to round it off. Since multiplying gives you 498.99998, truncating leaves 498 instead of 499.
    that's what i mean... y would the multiplication give 98 when it's a full 99... 4.99 isn't 4.9899999 or whatnot.. this eludes me

  14. #14
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    4.99 isn't 4.9899999 or whatnot.. this eludes me
    Except that it is, at least on a computer. Just like if I asked you to write down 1/3 as a decimal, you wouldn't ever be able to stop, if I asked you to write 4.99 in binary you wouldn't be able to stop. It's a repeating decimal, and if we only keep a finite amount we get 4.9899998.

  15. #15
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by OrAnGeWorX View Post
    4.99 isn't 4.9899999 or whatnot.. this eludes me
    4.99 != 4.9899998 to you. But remember that computers are dumber (though faster) than the average human being. You can just say: "That number is 4.99". A computer needs to represent that in binary, which is actually quite difficult, so it's approximated.
    This is why you should avoid working with floats and doubles wherever you can. They can lead to some evil old problems.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  2. C or C++
    By AcerN30 in forum Game Programming
    Replies: 41
    Last Post: 05-30-2008, 06:57 PM
  3. Another weird error
    By rwmarsh in forum Game Programming
    Replies: 4
    Last Post: 09-24-2006, 10:00 PM
  4. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  5. oh me oh my hash maps up the wazoo
    By DarkDays in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 12:54 PM