输入一个日期与超市系统中已经录入的商品日期作比较

输入一个日期与超市系统中已经录入的商品生产日期作比较,找出过期商品,并输出过期商品的信息

首先初始化了一个包含3个商品信息的结构体数组 goods,然后要求用户输入日期。接下来,我们遍历商品数组中的每个元素,将商品的生产日期加上保质期,得到过期日期。如果输入的日期晚于过期日期,则输出该商品的名称和过期日期。

#include <iostream>
#include <string>
using namespace std;

struct Good {
    string name;
    int year, month, day;
    int shelfLife;
};

int main() {
    // 初始化商品信息
    Good goods[3] = {
        {"Apple", 2022, 4, 30, 7},
        {"Banana", 2022, 5, 1, 5},
        {"Orange", 2022, 4, 20, 4}
    };

    // 输入日期
    int year, month, day;
    cout << "Enter the date (yyyy mm dd): ";
    cin >> year >> month >> day;

    // 比较日期并输出过期商品信息
    cout << "Expired goods:" << endl;
    for (int i = 0; i < 3; i++) {
        // 将商品的生产日期加上保质期,得到过期日期
        int expireYear = goods[i].year + goods[i].shelfLife / 365;
        int expireMonth = goods[i].month + (goods[i].shelfLife % 365) / 30;
        int expireDay = goods[i].day + (goods[i].shelfLife % 365) % 30;
        if (year > expireYear ||
            (year == expireYear && month > expireMonth) ||
            (year == expireYear && month == expireMonth && day > expireDay)) {
            // 商品已经过期
            cout << goods[i].name << " expired on "
                 << goods[i].year << "/" << goods[i].month << "/" << goods[i].day << endl;
        }
    }

    return 0;
}