Reputation: 57
My code produces an unexpected result in runtime. The purpose of the program is a cash dispenser which can only give out multiples of 20, rounded to the nearest multiple based on the user input.
I don't really understand what is going wrong, but the code does ask for the first user input and calls the ATM function first. I think it may be something to do with the scanf() calls but unsure.
#define MULT 20
unsigned int ATM(unsigned int cashRequest);
unsigned int roundUp(unsigned int numbToRoundUp);
unsigned int roundDown(unsigned int numbToRoundDown);
void test(void);
int main(void) {
test();
unsigned int a;
printf("How much would you like to withdraw?\n");
if (scanf("%u", &a) > 1)
ATM(a);
else
return 1;
return 0;
}
unsigned int ATM(unsigned int cashRequest) {
unsigned int higherBound;
unsigned int lowerBound;
if (cashRequest % MULT == 0 && cashRequest > 0) {
printf("Ok, dispensing: £%i\n", cashRequest);
return cashRequest;
} else if (cashRequest % MULT != 0) {
higherBound = roundUp(cashRequest);
lowerBound = roundDown(cashRequest);
printf("Sorry, multiples of £20 only available to deposit\n"
"Please choose either £%i [1] or £%i [2]\n " , higherBound, lowerBound);
int option;
while (scanf("%d", &option)) {
if (option == 1) {
printf("Ok, dispensing: £%i\n", higherBound);
} else if (option == 0) {
printf("Ok, dispencing: £%i\n", lowerBound);
} else {
printf("Incorrect input");
return 1;
}
}
} else if (cashRequest < MULT) {
printf("Sorry, £20 minimum deposit only, would you like £20[1] or try again[2]\n");
int option2;
while (scanf("%d", &option2)) {
if (option2 == 1) {
printf("Ok, dispensing %d", MULT);
} else if (option2 == 0) {
return 1;
}
}
}
return 1;
}
unsigned int roundUp(unsigned int numbToRoundUp) {
int remainder;
remainder = numbToRoundUp % MULT;
return numbToRoundUp + MULT - remainder;
}
unsigned int roundDown(unsigned int numbToRoundDown) {
assert(numbToRoundDown > MULT);
return (numbToRoundDown / MULT) * MULT;
}
output:
Sorry, multiples of £20 only available to deposit
Please choose either £180 [1] or £160 [2]
Upvotes: 0
Views: 73
Reputation: 356
The problem lies in this instruction:
if (scanf("%u", &a) > 1)
In fact, the scanf returns the number of items correctly assigned, in your example, given the scanf succedes, will return 1, so the function ATM cannot get called. You should directly test the variable (after the scanf):
if (a > 1)
Upvotes: 2