题中并没有说明库存量为正整数,so,要定义为double型。
该问题(定义变量类型问题)需要熟记
#include<iostream>
#include<algorithm>
using namespace std;
struct Invent{
double inventory; // 定义为int型会出错
double price, perprice;
}invent[1000];
bool cmp(Invent a, Invent b) {
if(a.perprice != b.perprice) return a.perprice > b.perprice;
else return a.inventory > b.inventory;
}
int main() {
int n;
double m;
cin >> n >> m;
for(int i=0;i<n;i++) {
cin >> invent[i].inventory;
}
for(int i=0;i<n;i++) {
cin >> invent[i].price;
}
for(int i=0;i<n;i++) {
invent[i].perprice = invent[i].price /invent[i].inventory;
}
sort(invent, invent+n, cmp);
double total = 0;
for(int i=0; i<n; i++) {
if(m <= invent[i].inventory) {
total += invent[i].perprice * m;
printf("%.2lf", total);
return 0;
} else {
m -= invent[i].inventory;
total += invent[i].price;
}
}
printf("%.2lf", total);
return 0;
}