Change calculation in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • orangeworx
    New Member
    • Nov 2008
    • 18

    Change calculation in C

    Hey guys, I'm not really a beginner in this, i can read and write code with enough ease but this is a whole new thing for me... i've written some code to give me the exact number of change (coins) when giving a number between 0 (inclusive) and 5 (non-inclusive)
    the problem i'm having is, for example, when i put certain numbers, i'm getting a wrong count of change... off by 1 penny only
    it's very bizarre...

    Code:
    #include <stdio.h>
    
    main()
    
    {
       // initialisation des variables
       int nbrMax;                        // Nbr d'entiers à saisir
       int tableauNbr[nbrMax-1];          // Tableau pour contenir les nombres entrés par l'usager
       int i;                             // Compteur boucle
       int j, k, somme;                   // variables pour calcul nbr parfait
       char condition;                    // Oui ou Non
    
       // Boucle do ... while, pour ne pas devoir repartir le programme pour chaque calcul
       do
          {
          printf ("Entrez le nombre d'entier (Max 10):\n");
          scanf ("%d", &nbrMax);
    
          // boucle pour la saisie des nombres et remplissage le tableau.
          for (i = 0; i < nbrMax; i++)
              {
              scanf ("%d", &tableauNbr[i]);
              }
    
          // Calculs pour trouver les nombres parfaits
          somme = 0;
          for (j = 0; j < nbrMax; j++)
              {
                for (k = 1; k < tableauNbr[j]; k++)
                    {
    					if(tableauNbr[j]%k==0)
    						{
    						somme += k;
    						}
          }
    				// Affichage des resultats
    				    if (somme = tableauNbr[j])
    						printf("%d est un nombre parfait\n", tableauNbr[j]);
    					    else
    						printf("%d n'est pas un nombre parfait\n", tableauNbr[j]);
    				
    		  }	
          
    
    
    
          // Condition requise pour repartir du début
          printf ("\nVoulez vous faire un autre calcul, (o/n)?");
          fflush (stdin);                        // Fonction pour vider stdin
          condition = toupper(getchar());        // Capitaliser la letter et soumettre à condition
          }
       while ( condition == 'O');                // Repartir du début si O
    
       system("pause") ;
    }
    I hope some1 can give me some insight on this

    Thanks in advance
    Marc
  • orangeworx
    New Member
    • Nov 2008
    • 18

    #2
    oh wow i am an idiot... pasted the wrong code....

    here's the actual one
    Code:
    #include <stdio.h>
    
    main ()
    
    {   // initialisation des variables
    
       float monnaie;                            // Nombre entré par usager
       int cents=0;                                // variable utilisé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èces
    
       do              // boucle de validation (monnaie entre 0 inclus et 5 non inclus)
         {
            printf("Entrez le montant a remettre: (x.xx)");     // Entré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 = toInt(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ébut
            printf ("\nVoulez vous faire un autre calcul, (o/n)?");
            fflush (stdin);                        // Fonction pour vider stdin
            condition = toupper(getchar());        // Capitaliser la letter et soumettre à condition
          
    	  } while ( condition == 'O');             // Repartir du début si O
    
    
       system("pause") ;
    }

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      Code:
      main ()
      Main returns int... ALWAYS.

      Code:
               fflush(stdin);                                      // vider la memoire temp.
               scanf("%f", monnaie);
      Don't fflush any input stream or any input/output stream where the last operation was an input. The result is undefined and therefore non-portable read this. You may also want to follow the link and read about why you shouldn't use scanf as well.

      Code:
                     cents = toInt(monnaie * 100);        // pour faciliter les calculs
      I don't know what your toInt function does but unless it takes account of rounding errors you can get when using floating point then this line is almost certainly where your calculation is going out by 1. Try adding 0.5

      Code:
          system("pause") ;
      This is very poor style and in a utility program a pain as the program could not be called without manual intervention. Most people who put this in do so because they do not properly know how their IDE works. They think that when they run the program from the IDE it does not stop so they can't see the output. In reality with most IDEs when you debug the program it does not stop but if you are debugging the assumption is that you are going to have a break point in the program to stop it. If you actually run the program (rather than debugging it) then the console stops at the end of program execution without this line.

      On MSVC debug-run is F5 but run is CTRL-F5

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        I haven't seen change done this way. Usually, you see for example: 1234

        Code:
        int dollars = money / 100;
        money = money -  dollars * 100;
        
        int quarters = money / 25;
        money = money - quarters * 25;
        
        etc..

        Comment

        • orangeworx
          New Member
          • Nov 2008
          • 18

          #5
          Originally posted by Banfa
          Code:
          main ()
          Main returns int... ALWAYS.

          agreed
          Code:
                   fflush(stdin);                                      // vider la memoire temp.
                   scanf("%f", monnaie);
          Don't fflush any input stream or any input/output stream where the last operation was an input. The result is undefined and therefore non-portable read this. You may also want to follow the link and read about why you shouldn't use scanf as well.
          had to use fflush because when a number outside the range was inputted, that number stuck in memory and gave erroneous change results
          Originally posted by Banfa
          Code:
                         cents = toInt(monnaie * 100);        // pour faciliter les calculs
          I don't know what your toInt function does but unless it takes account of rounding errors you can get when using floating point then this line is almost certainly where your calculation is going out by 1. Try adding 0.5
          i realized after my post that I was using an imaginary function.... and the 0.5, as i've looked it up, was the solution given to float to int conversions, oh didn't i mention i was really rusty...
          Originally posted by Banfa
          Code:
              system("pause") ;
          This is very poor style and in a utility program a pain as the program could not be called without manual intervention. Most people who put this in do so because they do not properly know how their IDE works. They think that when they run the program from the IDE it does not stop so they can't see the output. In reality with most IDEs when you debug the program it does not stop but if you are debugging the assumption is that you are going to have a break point in the program to stop it. If you actually run the program (rather than debugging it) then the console stops at the end of program execution without this line.
          that line was added by Dev-C++ and i don't think the teacher knew what he was talking about when he explained it. now it makes all the sense.
          but maybe for the purpose of the class and the programs being simple....

          any how thanks again, it's been a great help

          Comment

          • orangeworx
            New Member
            • Nov 2008
            • 18

            #6
            Originally posted by weaknessforcats
            I haven't seen change done this way. Usually, you see for example: 1234

            Code:
            int dollars = money / 100;
            money = money -  dollars * 100;
            
            int quarters = money / 25;
            money = money - quarters * 25;
            
            etc..
            it's canadian dollars and we have 2 and 1 dollar coins... :P

            Comment

            • orangeworx
              New Member
              • Nov 2008
              • 18

              #7
              Originally posted by JosAH
              There's more; look here near the start of main():

              Code:
                 int nbrMax;                        // Nbr d'entiers à saisir 
                 int tableauNbr[nbrMax-1];          // Tableau pour contenir les nombres entrés par l'usager
              nbrMax isn't initialized (yet).

              kind regards,

              Jos
              If i set nbrMax to 0 there and get the user input affected to it... should work right?

              Comment

              • vmpstr
                New Member
                • Nov 2008
                • 63

                #8
                (In addition to what has been said)

                Code:
                        scanf("%f", monnaie);
                that should be

                Code:
                       scanf("%f", &monnaie);

                Comment

                Working...