【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
原文地址:https://www.cnblogs.com/huangming-zzz/p/11700448.html