473,382 Members | 1,332 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

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...

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdio.h>
  3.  
  4. main()
  5.  
  6. {
  7.    // initialisation des variables
  8.    int nbrMax;                        // Nbr d'entiers à saisir
  9.    int tableauNbr[nbrMax-1];          // Tableau pour contenir les nombres entrés par l'usager
  10.    int i;                             // Compteur boucle
  11.    int j, k, somme;                   // variables pour calcul nbr parfait
  12.    char condition;                    // Oui ou Non
  13.  
  14.    // Boucle do ... while, pour ne pas devoir repartir le programme pour chaque calcul
  15.    do
  16.       {
  17.       printf ("Entrez le nombre d'entier (Max 10):\n");
  18.       scanf ("%d", &nbrMax);
  19.  
  20.       // boucle pour la saisie des nombres et remplissage le tableau.
  21.       for (i = 0; i < nbrMax; i++)
  22.           {
  23.           scanf ("%d", &tableauNbr[i]);
  24.           }
  25.  
  26.       // Calculs pour trouver les nombres parfaits
  27.       somme = 0;
  28.       for (j = 0; j < nbrMax; j++)
  29.           {
  30.             for (k = 1; k < tableauNbr[j]; k++)
  31.                 {
  32.                     if(tableauNbr[j]%k==0)
  33.                         {
  34.                         somme += k;
  35.                         }
  36.       }
  37.                 // Affichage des resultats
  38.                     if (somme = tableauNbr[j])
  39.                         printf("%d est un nombre parfait\n", tableauNbr[j]);
  40.                         else
  41.                         printf("%d n'est pas un nombre parfait\n", tableauNbr[j]);
  42.  
  43.           }    
  44.  
  45.  
  46.  
  47.  
  48.       // Condition requise pour repartir du début
  49.       printf ("\nVoulez vous faire un autre calcul, (o/n)?");
  50.       fflush (stdin);                        // Fonction pour vider stdin
  51.       condition = toupper(getchar());        // Capitaliser la letter et soumettre à condition
  52.       }
  53.    while ( condition == 'O');                // Repartir du début si O
  54.  
  55.    system("pause") ;
  56. }
  57.  
I hope some1 can give me some insight on this

Thanks in advance
Marc
Nov 17 '08 #1
7 2091
oh wow i am an idiot... pasted the wrong code....

here's the actual one
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. main ()
  4.  
  5. {   // initialisation des variables
  6.  
  7.    float monnaie;                            // Nombre entré par usager
  8.    int cents=0;                                // variable utilisée pour les calculs
  9.    int validation;
  10.    char condition;
  11.    // Boucle do ... while, pour ne pas devoir repartir le programme pour chaque calcul
  12.    do
  13.      {
  14.         int toonies=0;
  15.         int loonies=0;
  16.         int quarters=0;
  17.         int dimes=0;
  18.         int nickels=0;
  19.         int pennies=0;
  20.         // Nbr de pièces
  21.  
  22.    do              // boucle de validation (monnaie entre 0 inclus et 5 non inclus)
  23.      {
  24.         printf("Entrez le montant a remettre: (x.xx)");     // Entrée du change a remettre
  25.         fflush(stdin);                                      // vider la memoire temp.
  26.         scanf("%f", monnaie);
  27.  
  28.         validation = ( monnaie >= 0 && monnaie < 5);
  29.  
  30.         if (!validation)   // si pas vrai
  31.         printf ("Montant de change non valide! SVP le retaper. \n");
  32.  
  33.       } while (!validation);       // tant que non valide
  34.  
  35.       // Calculs
  36.               cents = toInt(monnaie * 100);        // pour faciliter les calculs
  37.             while (cents >= 200) {
  38.                 toonies++;
  39.                 cents -= 200;
  40.             }
  41.             while (cents >= 100) {
  42.                 loonies++;
  43.                 cents -= 100;
  44.             }
  45.             while (cents >= 25) {
  46.                 quarters++;
  47.                 cents -= 25;
  48.             }
  49.             while (cents >= 10) {
  50.                 dimes++;
  51.                 cents -= 10;
  52.             }
  53.             while (cents >= 5) {
  54.                 nickels++;
  55.                 cents -= 5;
  56.             }
  57.             while (cents >=1) {
  58.                 cents++;
  59.                 cents-=1;
  60.                 } 
  61.       // Affichage des resultats
  62.         printf ("Vous aurez: \n");
  63.         printf ("%d pieces de 2$, \n", toonies);
  64.         printf ("%d pieces de 1$, \n", loonies);
  65.         printf ("%d pieces de 25c, \n", quarters);
  66.         printf ("%d pieces de 10c, \n", dimes);
  67.         printf ("%d pieces de 5c \n", nickels);
  68.         printf ("et \n%d pieces de 1c", pennies);
  69.  
  70.       // Condition requise pour repartir du début
  71.         printf ("\nVoulez vous faire un autre calcul, (o/n)?");
  72.         fflush (stdin);                        // Fonction pour vider stdin
  73.         condition = toupper(getchar());        // Capitaliser la letter et soumettre à condition
  74.  
  75.       } while ( condition == 'O');             // Repartir du début si O
  76.  
  77.  
  78.    system("pause") ;
  79. }
  80.  
Nov 17 '08 #2
Banfa
9,065 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. main ()
Main returns int... ALWAYS.

Expand|Select|Wrap|Line Numbers
  1.          fflush(stdin);                                      // vider la memoire temp.
  2.          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.

Expand|Select|Wrap|Line Numbers
  1.                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

Expand|Select|Wrap|Line Numbers
  1.     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
Nov 17 '08 #3
weaknessforcats
9,208 Expert Mod 8TB
I haven't seen change done this way. Usually, you see for example: 1234

Expand|Select|Wrap|Line Numbers
  1. int dollars = money / 100;
  2. money = money -  dollars * 100;
  3.  
  4. int quarters = money / 25;
  5. money = money - quarters * 25;
  6.  
  7. etc..
  8.  
Nov 17 '08 #4
Expand|Select|Wrap|Line Numbers
  1. main ()
Main returns int... ALWAYS.

agreed
Expand|Select|Wrap|Line Numbers
  1.          fflush(stdin);                                      // vider la memoire temp.
  2.          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
Expand|Select|Wrap|Line Numbers
  1.                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...
Expand|Select|Wrap|Line Numbers
  1.     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
Nov 17 '08 #5
I haven't seen change done this way. Usually, you see for example: 1234

Expand|Select|Wrap|Line Numbers
  1. int dollars = money / 100;
  2. money = money -  dollars * 100;
  3.  
  4. int quarters = money / 25;
  5. money = money - quarters * 25;
  6.  
  7. etc..
  8.  
it's canadian dollars and we have 2 and 1 dollar coins... :P
Nov 17 '08 #6
There's more; look here near the start of main():

Expand|Select|Wrap|Line Numbers
  1.    int nbrMax;                        // Nbr d'entiers à saisir 
  2.    int tableauNbr[nbrMax-1];          // Tableau pour contenir les nombres entrés par l'usager 
  3.  
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?
Nov 17 '08 #7
vmpstr
63
(In addition to what has been said)

Expand|Select|Wrap|Line Numbers
  1.         scanf("%f", monnaie);
  2.  
that should be

Expand|Select|Wrap|Line Numbers
  1.        scanf("%f", &monnaie);
  2.  
Nov 18 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: Aspersion | last post by:
I'm building an ASP page that has a lot of text and graphics. There is a calculation facility on the page. The user enters several numbers in a form and presses a button to see the calculated...
0
by: anaxamandr | last post by:
Hi. I have a long loop in ASP that performs a rather lengthy calculation. I would love for my users to be able to stop that calculation, if they so choose, mid way through the process. I attempted...
2
by: Del | last post by:
Thanks in advance for any help. I have a database that was created in Access 2000. Several users have been upgraded to Access 2003. Since upgrading to 2003 we have noticed that some of the...
4
by: Michiel Alsters | last post by:
Hello everybody, I hope anybody can help me. I'll try to give a brief overview of my problem. I have running a program that performs a heavy calculation. To give the user feedback what the...
1
by: Gordon | last post by:
Hi there, I have a VB.NET application which opens a new Excel workbook (and obviously worksheet). The cell values in the worksheet depend on certain formulae, therefore the sheet Calculate event...
2
cassbiz
by: cassbiz | last post by:
I may be in the wrong forum so Ronald don't shoot :) In my code I have an option box to choose a number - works fine. I want to carry over the new value to another field to do a recalculation. ...
4
by: gregincolumbus | last post by:
I am trying to get the financial calculation on this to trigger whenever there is a change to select1. Right now, the user has to click on select2 to trigger the changes. Ideally, a change of...
3
by: mattmao | last post by:
Okay, I was asked by a friend about the result of this limit: http://bbs.newwise.com/attdata/forumid_14/20070922_fe7f77c81050413a20fbDWYOGm7zeRj3.jpg Not n->zero but n-> + infinite I really...
8
by: mlwerth | last post by:
Dear Access Group: This is the most basic and most embarrassing of questions, but I cannot find where to change the data type of a text field that I have in Access 2003 to a number field. I've...
4
by: Lara1 | last post by:
I'm trying to write a procedure that will enable button on a sheet (and colour it red), but ONLY when changes are made to cells in column E of that sheet (from row 10 to the bottom of the...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.