tags:

views:

61

answers:

2

Hi,

I just recently started studying Objective-C (or programming for that matter) and am stuck at a simple program.

I'm trying to create change in quarters, dimes, nickels, and pennies but noticed that the solution I came up with would give random value to nickels or pennies.

Ex. Change for 25 would come out to "The change is 1 quarter, 0 dime, -1881139893 nickels, and 4096 pennis"

Ex2. Change for 30 would come out to "The change is 1 quarter, 0 dime, 1 nickels, and 4096 pennis"

What can I add/change to fix this behavior?

Also, is there any better solution then having to run 4 different if statements?

Thanks!

Here's my code below:

int orig, q, d, n, p;

NSLog(@"Give money to make change");
scanf("%i", &orig);

if(orig >= 25) {
    q = orig/25;
    orig -=  q*25;
}
if(orig >= 10 && orig < 25) {
    d = orig/10;
    orig -= d*10;
}
if(orig >= 5 && orig < 10) {
    n = orig/5;
    orig -= n*5;
}
if(orig >= 1 && orig < 5) {
    p = orig;
}

NSLog(@"The change is %i quarter, %i dime, %i nickels, and %i pennis", q, d, n, p);
+2  A: 

You should make use of modulus instead. I don't want to ruin your learning experience so this is an example of how you can use modulus to calculate days, hours, minutes and seconds for time given in seconds only.

int x = 1123123; 
int seconds = x % 60;
x /= 60;
int minutes = x % 60;
x /= 60;
int hours = x % 24;
x /= 24;
int days = x;

Now apply it to your problem :)

Merrimack
Will try that out. Thanks for the suggestion! Really helps to get pointers like this. :)
Hyung Suh
+3  A: 

You don't initialize your variables to start with, so they all start with random values, then in your code, in the case where there's no pennys, you never set p to anything, so it retains its initial random value, which you then see in your output. You can fix it by initializing your variables at the start.

int orig=0, q=0, d=0, n=0, p=0;
superfell
I see, I did realize that setting it's initial value to 0 helped the solution, however, it seems like DIME would always be 0 even if i didnt set an initial value? Will make sure to keep that in mind in the future. Thanks.
Hyung Suh
@Hyung: it's not really random, it's what was in that memory location before. If you call a function that just initializes a lot of local variables to (say) 42, and then returns, and _directly on return_ you call your change-making function, you'd likely see 42's for your number of dimes.
Aidan Cully
@Hyung Suh: As Aidan said, it's not random, but it's not reliable either. It's just *likely* to work that way on most computers. Just FYI.
Chuck