本来很简单的一道题,都是自己考虑不周全所至啊!我刚开始每一次输入都进行一次排序,然后求出其平均值,从头至尾把大于平均值的数与平均值的差值相加,但是也有可能从数组的另一头反着算会是较小的。于是……
#include<cstdio>
#include<cstdlib>
double a[1005];
char tmp[1005];//用于截取小数点后前两位时用
int main(void)
{
int n = 0;
while(scanf("%d",&n) == 1)
{
if(n == 0) break;//如果输入为0,结束
double trans1 = 0.0,trans2= 0.0;
double addall = 0.0;
for(int i = 0;i < n;i ++)
{
scanf("%lf",&a[i]);
addall += a[i];
}
double average = addall/n;
sprintf(tmp,"%.2lf",average);
sscanf(tmp,"%lf",&average);
for(int i = 0;i < n; i++)
{
if(a[i] > average) trans1 += (a[i]-average);
else trans2 += (average -a[i]);
}
trans1 > trans2? printf("$%.2lf/n",trans2):printf("$%.2lf/n",trans1);
}
return 0;
}