$11.99
思路:首先想到的是要想知道交易总和最少,我必须解出平均每个人出多少,平均数解出来,根据题意精确到1美分,即0.01,然后根据多退少补的方式,求得结果,一个细节是,我们要考虑四种情况:情况一:当多退少补都为零;情况二:当多退为零,少补不为零时;情况三:当少补为零,多退不为零时;四:当多退少补都为零。
个人代码:
#include <stdio.h> #define SIZE 1000 double findChange(double *money, int total) { double average = 0.0, changeDown = 0.0, changeUp = 0.0, change = 0.0; int i; for (i = 0; i < total; i++) average += money[i]; average /= total; average = (long) (average * 100 + 0.5) / 100.00; for (i = 0; i < total; i++) { if (money[i] > average) changeUp += (money[i] - average); else changeDown += (average - money[i]); } if (changeDown > 0 && changeUp > 0) { if (changeDown > changeUp) change = changeUp; else change = changeDown; } else //如果一边有零 { if (changeUp == 0 && changeDown == 0)//两边都为零 change = 0.0; else { if (changeDown == 0)//少补为零时 { for ( i = 0; i < total; i++) if (money[i] > average) change += (money[i] - average - 0.01); } else //多退为零时 { for ( i = 0; i < total; i++) if (money[i] < average) change += (average - money[i] - 0.01); } } } return change; } int main() { double money[SIZE], result = 0.0; int total,i; while (scanf("%d",&total) != 0) { for ( i = 0; i < total; i++) scanf("%f",&(money[i])); result = findChange(money, total); printf("$%0.2f\n",result); } return 0; }
正确代码:
#include <stdio.h> float get_aveg(float a); int main(){ int count; int i; float sum,aveg,changeup,changedown,result; while(scanf("%d",&count) != 0 && 0 < count && count < 1000){ sum = 0.00; result = 0.00; float fate[count]; for (i =0;i < count;i++){ scanf("%f",&fate[i]); while(fate[i] > 100000) scanf("%f",&fate[i]); } for (i =0;i < count;i++){ sum += fate[i]; } aveg = sum/count; aveg = get_aveg(aveg); for (i =0;i < count;i++){ if(fate[i] > aveg) changeup += (fate[i]- aveg); if(fate[i] < aveg) changedown +=(aveg - fate[i]); } if (changedown > 0 && changeup > 0) { if (changedown > changeup) result = changeup; else result = changedown; } else //如果一边有零 { if (changeup == 0 && changedown == 0)//两边都为零 result = 0.0; else { if (changedown == 0)//少补为零时 { result = 0.00; /*for ( i = 0; i < count; i++) if (fate[i] > aveg) result += (fate[i] - aveg - 0.01); */ } else //多退为零时 { result = 0.00; /*for ( i = 0; i < count; i++) if (fate[i] < aveg) result += (aveg - fate[i] - 0.01); */ } } } printf("$%0.2f",result); } } float get_aveg(float a){ int b ; float c; b = a*1000; if(b % 10 >= 5){ b= b/10 + 1; c = (float)b /100; } else { b = b/10; c = (float)b /100; } return c; }
目前根据测试并没有错误,但是提交出现WA。暂未解决。