写PATB1020的时候,学到了点新东西。
但是不知道为什么结构体从1开始赋值再用sort会出错,但是从0开始就没事。
特此记录下。
本部分代码大意:
输入n,d(前边用不到)
代表有n种月饼
接着输入每种月饼的总储存量
再输入每种月饼的总售价
按照单价递减的顺序输出每种月饼的总储存量和总售价
先上错误的
#include <bits/stdc++.h>
using namespace std;
struct mooncakes{
double store; //sum store
double sell; //sum sell
double price; //single price
}cake[1010];
bool cmp(mooncakes a,mooncakes b){
return a.price>b.price;
}
int main(){
int n,d;
cin>>n>>d;
for (int i=1;i<=n;i++)
scanf("%lf",&cake[i].store);
for (int i=1;i<=n;i++){
scanf("%lf",&cake[i].sell);
cake[i].price=cake[i].sell/cake[i].store;
}
sort(cake,cake+n+1,cmp); //中间的为末元素地址加一
for (int i=1;i<=n;i++)
printf("%.3lf %.3lf\n",cake[i].store,cake[i].sell); //输出排序后的结构体
}
但是发现输出错误了
若是从i=0开始赋值,代码段为
#include <bits/stdc++.h>
using namespace std;
struct mooncakes{
double store; //sum store
double sell; //sum sell
double price; //single price
}cake[1010];
bool cmp(mooncakes a,mooncakes b){
return a.price>b.price;
}
int main(){
int n,d;
cin>>n>>d;
for (int i=0;i<n;i++)
scanf("%lf",&cake[i].store);
for (int i=0;i<n;i++){
scanf("%lf",&cake[i].sell);
cake[i].price=cake[i].sell/cake[i].store;
}
sort(cake,cake+n,cmp);
for (int i=0;i<n;i++)
printf("%.3lf %.3lf\n",cake[i].store,cake[i].sell);
}
输出结果则正确
好奇怪