ZBLOG

#include #include #include #include struct Purchase { std::string date; std::string product; double price; }; bool compareDates(const Purchase& p1, const Purchase& p2) { return p1.date > p...

要修改代码以比较月日距离现在的远近,您需要使用日期时间库(如<chrono>)和当前日期时间进行比较。下面是修改后的代码示例:

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. #include <chrono>
  6. struct Purchase {
  7. std::string date;
  8. std::string product;
  9. double price;
  10. };
  11. // 比较两个日期之间的天数差距
  12. int compareDates(const std::string& date1, const std::string& date2) {
  13. // 解析日期字符串为std::tm结构体
  14. std::tm tm1 = {};
  15. strptime(date1.c_str(), "%Y-%m-%d", &tm1);
  16. std::tm tm2 = {};
  17. strptime(date2.c_str(), "%Y-%m-%d", &tm2);
  18. // 将std::tm转换为std::chrono::system_clock时间点
  19. auto timePoint1 = std::chrono::system_clock::from_time_t(std::mktime(&tm1));
  20. auto timePoint2 = std::chrono::system_clock::from_time_t(std::mktime(&tm2));
  21. // 计算时间点之间的天数差距
  22. auto duration = timePoint1 - timePoint2;
  23. return duration / (std::chrono::hours(24));
  24. }
  25. bool compareDatesWithCurrent(const Purchase& p) {
  26. // 获取当前日期时间
  27. auto nowTimePoint = std::chrono::system_clock::now();
  28. // 转换为当地时间结构体
  29. time_t nowTimeT = std :: chrono :: system_clock :: to_time_t(nowTimePoint);
  30. std :: tm now = * localtime( & nowTimeT);
  31. now.tm_year += 1900; // 年份要加上1900
  32. now.tm_mon += 1; // 月份要加1
  33. return compareDates(p.date, std::to_string(now.tm_year) + "-" + std::to_string(now.tm_mon) + "-" + std::to_string(now.tm_mday)) > 0;
  34. }
  35. double calculateAveragePrice(const std::vector<Purchase>& purchases, const std::string& product, int N) {
  36. double sum = 0.0;
  37. int count = 0;
  38. for (const Purchase& purchase : purchases) {
  39. if (purchase.product == product && compareDatesWithCurrent(purchase)) {
  40. sum += purchase.price;
  41. count++;
  42. if (count == N) break;
  43. }
  44. }
  45. return (count > 0) ? sum / count : 0.0;
  46. }
  47. int main() {
  48. int m, n;
  49. std::cin >> m >> n;
  50. std::vector<Purchase> purchases(m);
  51. for (int i = 0; i < m; i++) {
  52. std::cin >> purchases[i].date >> purchases[i].product >> purchases[i].price;
  53. }
  54. double keyboardAvgPrice = calculateAveragePrice(purchases, "keyboard", n);
  55. double mouseAvgPrice = calculateAveragePrice(purchases, "mouse", n);
  56. std::cout << std::fixed;
  57. std::cout.precision(1);
  58. std::cout << keyboardAvgPrice << std::endl;
  59. std::cout << mouseAvgPrice << std::endl;
  60. return 0;
  61. }

请注意,这里使用了C++11标准的日期时间库,并假设输入的日期格式为”YYYY-MM-DD”。还使用strptime()函数将日期字符串解析为std::tm结构体,然后将其转换为std::chrono::system_clock时间点进行比较。最后,通过与当前日期进行比较来判断日期是否在当前日期之前。


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?