qq_33825615 于 2016.09.12 11:59 提问

PAT 中的基础题 1020. 月饼 (25)
`````` #include <stdio.h>
#include <stdlib.h>
struct mk
{
double storage;
double sumPrice;
double perPrice;
};
int cmp(const void *a,const void *b)           //用于qsort按照单价排序
{
struct mk m1 = *(struct mk*)a;
struct mk m2 = *(struct mk*)b;
return m2.perPrice - m1.perPrice;
}
int main ()
{
int num;
double need;
double ret = 0.0;
scanf("%d %lf",&num,&need);
struct mk list[1100];
int i;
for(i = 0;i < num;i++)
{
scanf("%lf",&list[i].storage);
}
for(i = 0;i < num;i++)
{
scanf("%lf",&list[i].sumPrice);
}
for(i = 0;i < num;i++)                       //以上为输入
{
list[i].perPrice = list[i].sumPrice/list[i].storage;
}
qsort(list,num,sizeof(list[0]),cmp);
i = 0;
while(need != 0)
{
if(need > list[i].storage)          //需求大于库存
{
need = need - list[i].storage;
ret = ret + list[i].sumPrice;
if( i == num-1)                     //全部用完还是没满足需求
{
need = 0;
}
}
else                       //需求小于库存
{
ret = ret + list[i].perPrice * need;
need = 0;
}
i++;
}
printf("%.2lf\n",ret);
return 0 ;
}

``````

1个回答

int cmp() 最后一行
return m2.perPrice - m1.perPrice;

return m2.perPrice > m1.perPrice?1:-1;

perPrice是都double类型的,cmp返回值是int,计算m2.perPrice - m1.perPrice会有误差.

qq_33825615 啊，非常感谢啊。谢谢了，我找了一上午也没发现，看来基本功还是太差。 谢谢！