2 qq 33825615 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 ;
}

实在是不知道第一个测试点哪里错了,其他都对啊。跪求大神解答

题目连接https://www.patest.cn/contests/pat-b-practise/1020

1个回答

dead911
dead911   2016.09.12 12:59

排序算法的问题
int cmp() 最后一行
return m2.perPrice - m1.perPrice;
改成
return m2.perPrice > m1.perPrice?1:-1;

perPrice是都double类型的,cmp返回值是int,计算m2.perPrice - m1.perPrice会有误差.
比如计算出m2.perPrice-m1.perPrice = 0.1234,你期待return的是1,但实际被截断后return的时候是0.

qq_33825615
qq_33825615 啊,非常感谢啊。谢谢了,我找了一上午也没发现,看来基本功还是太差。 谢谢!
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片