/* Name: trip.c Purpose: Solution to Programming Challenges "The Trip" (# 10137) Author: Bill Slough Date: January 21, 2012 */ #include #define MAX_STUDENTS 1000 int main() { int d, c; /* dollars and cents */ int n; /* number of students for any one trip */ int i; /* loop index */ int amt[MAX_STUDENTS]; /* amount each student paid, in cents */ int total; /* total amount, in cents, for one trip */ int average; /* amount each student should pay for trip, not counting a possible extra cent */ int leftover; /* number of cents to distribute among students to make the total exact */ int toDistribute; /* amount of money to distribute to share the costs */ scanf("%d", &n); while (n != 0) { /* Collect and save the data for the current trip */ for (i = 0; i < n; i++) { scanf("%d.%d", &d, &c); amt[i] = 100*d + c; } /* Determine the total amount paid for this trip */ total = 0; for (i = 0; i < n; i++) { total = total + amt[i]; } /* Determine the average amount */ average = total/n; /* the FLOOR of the true average */ leftover = total % n; /* Examine what each student paid; determine the total amount to be repaid. */ toDistribute = 0; for (i = 0; i < n; i++) { if (amt[i] > average) { /* this student overpaid and needs reimbursement */ toDistribute = toDistribute + (amt[i] - average); /* To keep reimbursements lower, increase the cost of the overpayers by one penny */ if (leftover > 0) { toDistribute = toDistribute - 1; leftover = leftover - 1; } } } /* Announce the minimum amount which needs to be redistributed */ printf("$%d.%02d\n", toDistribute/100, toDistribute % 100); /* Get ready for the next group... */ scanf("%d", &n); } return 0; }