Monday, May 24, 2010

C++ keeping remainder of integer problem?

I'm coding a program for school, it is a vending machine. Bassically my program takes in an integer input (no floating point) from the user up to 2.00$ and then outputs the correct amount of coins to give back to the user (quarters,dimes,nickels). I've figured out how to display the coins on an integer, however i can't figure out how to keep the remainder of the integer after i get the intial cin %26gt;%26gt; from the user. If i put in 1.66 for example it just closes down the program. If anyone can help or point me in the direction of a tutorial i would appreciate it alot

C++ keeping remainder of integer problem?
I would guess that if you are allowing your user to input 1.66, and you must process everything in integer, then you need to parse the input as a string and generate two integer values that are added together.





For example, this small function will accept a character string and return the number of cents:





int buf2cents( char *buf )


{


int cents = 0;


char *token;





token = strchr( buf, '.' ); /* point at decimal */


*token++ = 0; /* convert into second string */


cents = atoi( buf ) * 100 /* convert dollar value into 100s of cents*/





if( token != NULL )


cents += atoi( token ); /* convert cents to integer and add */





return cents;


}





If you are keeping the price of your items as integers (cents) the change is simple subtraction, and it sounds like you have worked out how to do the math to know what coins to return.
Reply:try converting your input into floating point bec. your program's variables are initialized as integers and yet you put in floating point input. in short, the program is expecting integers and you give it floating point.


No comments:

Post a Comment