• 【PAT B1020】月饼 段错误->答案正确


    #include <algorithm>
    #include <stdio.h>
    #include <string.h>
    #include <fstream>
    #include <iostream>
    #include <string.h>
    #include <cstring>
    #include <vector>
    #include <math.h>
    #define maxnM 2000
    using namespace std;
    int N;
    double D;   //N <= maxM; D <= 500
    
    struct moonCake {
        double store;
        double price;
        double advPrice;
    } moonCakes[1010];
    
    bool cmp(moonCake m1, moonCake m2) {
        return m1.advPrice > m2.advPrice;
    }
    void showmoonCakes() {
        moonCake* p = moonCakes;
        for(int i = 0; i < N; i++) {
            printf("%d %lf %lf %lf
    ", i, p->store, p->price, p->advPrice);
            p++;
        }
        return;
    }
    
    void fileInput() {
        ifstream fin;
        fin.open("/home/zzz/input.txt", ios::in);
        fin >> N >> D;
        moonCake* p = moonCakes;
        for (int i = 0; i < N; i++) {
            fin >> p->store;
            p++;
        }
        p = moonCakes;
        for (int i = 0; i < N; i++) {
            fin >> p->price;
            p->advPrice = p->price / p->store  ;
            p++;
        }
        fin.close();
    }
    
    void StdInput() {
        cin >> N >> D;
        moonCake* p = moonCakes;
        for (int i = 0; i < N; i++) {
            cin >> p->store;
            p++;
        }
        p = moonCakes;
        for (int i = 0; i < N; i++) {
            cin >> p->price;
            p->advPrice = p->price / p->store;
            p++;
        }
    }
    
    double calcul() {
        double ans = 0, weight = 0;
        moonCake* p = moonCakes;
        while(weight < D) {
            double soldWeight = ( D - weight > p->store ? p->store : D-weight);
            weight += soldWeight;
            ans += soldWeight * p->advPrice;
            if((p+1) != NULL) p++;
        }
        return ans;
    }
    
    int main() {
        //fileInput();
        StdInput();
        sort(moonCakes, moonCakes + N, cmp);
        printf("%.2lf
    ", calcul());
        return 0;
    }
    

    - 段错误出现的可能 - 数组越界 - 类型的比较 - 除了题目中的表述,运算的过程中也要注意如果出现了数据的比较、运算也要变成double
  • 相关阅读:
    cmder
    navicat 查询保存的位置
    git使用
    怎么保证测试用例的覆盖率
    python3.7-初学篇-19-良好的习惯
    python基础篇-使用list和tuple
    python基础篇-字符串和编码
    python基础篇-输入和输出
    python3.7-初学篇-21
    python3.7-初学者-20
  • 原文地址:https://www.cnblogs.com/huangming-zzz/p/11700448.html
Copyright © 2020-2023  润新知