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);
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;
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 :)
精彩评论