Question 8
Back to Exercise
Write deposit and withdraw functions for an account structure that refuse invalid operations and report why.
Solution
#include <stdio.h>
enum result { OK, INVALID_AMOUNT, INSUFFICIENT_FUNDS };
struct account {
const char *owner;
long balance; /* in paise, to avoid floating-point rounding */
};
enum result deposit(struct account *a, long amount) {
if (amount <= 0)
return INVALID_AMOUNT;
a->balance += amount;
return OK;
}
enum result withdraw(struct account *a, long amount) {
if (amount <= 0)
return INVALID_AMOUNT;
if (amount > a->balance)
return INSUFFICIENT_FUNDS;
a->balance -= amount;
return OK;
}
int main(void) {
static const char *msg[] = {"ok", "invalid amount", "insufficient funds"};
struct account acc = {"Asha", 0};
printf("deposit 500.00: %s\n", msg[deposit(&acc, 50000)]);
printf("withdraw 800.00: %s\n", msg[withdraw(&acc, 80000)]);
printf("withdraw 120.50: %s\n", msg[withdraw(&acc, 12050)]);
printf("deposit -5.00: %s\n", msg[deposit(&acc, -500)]);
printf("%s's balance: %ld.%02ld\n", acc.owner, acc.balance / 100, acc.balance % 100);
return 0;
}
deposit 500.00: ok withdraw 800.00: insufficient funds withdraw 120.50: ok deposit -5.00: invalid amount Asha's balance: 379.50
Money is kept as whole paise in a long, because floating-point values cannot represent amounts like 0.10 exactly. An enum result tells the caller exactly why an operation failed, and indexes a message table.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!