Ponytai1 2016-09-12 03:59 采纳率: 25%
浏览 2038

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条回答 默认 最新

  • 呆的久 2016-09-12 04: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.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)