ZBLOG

#include #include #include #include #include #include #include using namespace std; struct Purchase { string date; string product; int price; }; // 自定义比较日期的函数,用于在排序时按...

下面是修改后的代码,使用’/‘分割日期字符串,并按照日期进行排序:

#include <vector>
#include <map>
#include <iomanip>
#include <string>
#include <sstream>
#include <algorithm>
#include <iostream>
using namespace std;

struct Purchase {
    string date;
    string product;
    int price;
};

// 自定义比较日期的函数,用于在排序时按日期升序排序
bool compareDates(const string& date1, const string& date2) {
    // 日期格式为"MM/DD",假设没有错误处理
    int month1 = stoi(date1.substr(0, 2)); // 提取月份部分并转换为整数
    int day1 = stoi(date1.substr(3, 2));   // 提取日期部分并转换为整数
    int month2 = stoi(date2.substr(0, 2)); // 提取月份部分并转换为整数
    int day2 = stoi(date2.substr(3, 2));   // 提取日期部分并转换为整数

    if (month1 != month2) {
        return month1 > month2; // 按月份升序排序
    }
    else if (day1 != day2) {
        return day1 > day2;     // 月份相同时按日期升序排序
    }
    
    return false; // 日期相同,不需要交换顺序
}

int main() {
    int m, n;
    
    while (cin >> m >> n) {
        vector<Purchase> purchases;

        for (int i = 0; i < m; i++) {
            Purchase p;
            cin.ignore(); // 忽略换行符
            getline(cin, p.date, '/');
            cin >> p.product >> p.price;
            purchases.push_back(p);
        }

        // 使用自定义的比较函数按日期升序排序购买记录
        sort(purchases.begin(), purchases.end(), [](const Purchase& a, const Purchase& b) {
            return compareDates(a.date, b.date);
        });

        double keyboardSum = 0, mouseSum = 0;
        int keyboardCount = 0, mouseCount = 0;

        for (int i = 0; i < m; i++) {
            if (purchases[i].product == "keyboard" && keyboardCount < n) {
                keyboardSum += purchases[i].price;
                keyboardCount++;
            }
            else if (purchases[i].product == "mouse" && mouseCount < n) {
                mouseSum += purchases[i].price;
                mouseCount++;
            }
        }

        // 计算平均价格时,使用键盘和鼠标各自的计数
        double keyboardAvg = (keyboardCount > 0) ? keyboardSum / keyboardCount : 0;
        double mouseAvg = (mouseCount > 0) ? mouseSum / mouseCount : 0;

        // 输出结果,保留一位小数
        cout << fixed << setprecision(1) << keyboardAvg << endl;
        cout << fixed << setprecision(1) << mouseAvg << endl;
    }
    
    return 0;
}

这样修改后,在输入日期时可以直接使用’/‘分割字符串,并且根据日期进行排序。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=9104

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?