Thursday, July 30, 2009

C++ Program, it's fun but just not getting it?

#include%26lt;iostream%26gt;


#include%26lt;iomanip%26gt;


using namespace std;








int dollar, quarter, nickel,penny;


double CostOfPurchase, AmountTendered, change, CHANGE;





int main ( )


{


cout%26lt;%26lt;"Enter cost of Purchase: "%26lt;%26lt;endl;


cin%26gt;%26gt; CostOfPurchase;


cout%26lt;%26lt;endl;


cout%26lt;%26lt;"Enter amount tendered: "%26lt;%26lt;endl;


cin%26gt;%26gt; AmountTendered;


cout%26lt;%26lt;endl;








change= AmountTendered - CostOfPurchase;


cout%26lt;%26lt;"The change is $"%26lt;%26lt; change%26lt;%26lt;endl;





(int)dollar= change/1.00;


(int)quarter=(change - dollar)/0.25;


(int)nickel=(change - dollar - quarter)/0.05;


(int)penny = nickel/0.01;





cout%26lt;%26lt; dollar%26lt;%26lt;" dollar"%26lt;%26lt;endl;


cout%26lt;%26lt; quarter%26lt;%26lt;" quarter"%26lt;%26lt;endl;


cout%26lt;%26lt; nickel%26lt;%26lt; " nickel"%26lt;%26lt;endl;


cout%26lt;%26lt; penny%26lt;%26lt; " penny" %26lt;%26lt;endl;


return 0;


}





Here is my attempt at this so far. I have to make a program to make change. I can have it make the change just fine. It is making it divide the change into dollars, quarters, and nickels, pennies.

C++ Program, it's fun but just not getting it?
Your problem is here:


(int)nickel=(change - dollar - quarter)/0.05;





You have a quarter worth as much as a dollar.


If your starting amount was $1.40, then


nickle = (1.40 -1 -1)/5 = -.8





I would do it in steps. It's easier to debug.





(int)dollars= change/1.00;


change = change - dollars;





(int)quarters= change)/0.25;


change = change - .25*quarters;





(int)nickels= change/0.05;


change = change - .05 * nickels;





(int)pennys = change/0.01;
Reply:ok simply dont use any doubles! (trust me the rounding errors will be a nitemare later) use int only and work in pennies rather than dollars. The only time to use doubles with money is if you want fractional pennies say if your writing code for the stock market.





So if we rewrite one of your lines with better variable names and a few tweaks we might get:


number_of_quarters = ( change - number_of_dollarbills ) / 25;





So how can we find the bug?


We will do whats called deskchecking and try to run the program on paper and in our heads. We go though each line and try to work out what the computer will do.





So if I spend $5.67 and pay with a $10 note then:


change = 1000 - 567 = 433


number_of_dollarbills = 433 / 100 = 4


number_of_quarters = (433 - 4) / 25 and we see the bug is in treating the number of dollar bills as if it we they amount in dollars, we should have had 433 - 400 instead





BTW Thats REALLY good coding if you've only been at it for 2 weeks!

tropical flowers

No comments:

Post a Comment