题解 | #网购(回调函数实现)#

网购

https://www.nowcoder.com/practice/5d7dfd405e5f4e4fbfdff6862c46b751

#include <stdio.h>
int checkDate(int monthInput, int dateInput);
double calcPrice(int (*checkDate)(int, int), \
                 int monthInput,             \
                 int dateInput,              \
                 int flagCoupon,             \
                 double price);
// @brief 集合决定价格的因素
struct PriceFactor {
    double price;
    int month, date;
    int flagCoupon;// 有优惠券为1,无优惠券为0
} shopping;

int main() {
    scanf("%lf %d %d %d", &shopping.price, \
                          &shopping.month, \
                          &shopping.date,  \
                          &shopping.flagCoupon);
    getchar(); // 吸收缓冲区的换行符,好习惯

    // 计算价格,赋值给shopping.price
    shopping.price = calcPrice(&checkDate, \
    shopping.month,                        \
    shopping.date,                         \
    shopping.flagCoupon, shopping.price);

    // 如果商品比较便宜,可能会出现用了优惠券价格成负数的情况!
    // 但是这不符合逻辑,因为商家不会倒给买家钱
    shopping.price > 0 ? (shopping.price = shopping.price) : (shopping.price = 0);
    printf("%.2lf\n", shopping.price);

    getchar();
    return 0;
}

// @brief 回调函数,在calcPrice中充当参数
// @param 月份 - 日子
int checkDate(int monthInput, int dateInput) {
    // 1为双11,2为双12
    if (monthInput == 11 && dateInput == 11) {
        return 1;
    } else if (monthInput == 12 && dateInput == 12) {
        return 2;
    }
    // 不符合输入要求
    return 0;
}

// @brief 求打折后价格
// @param checkDate函数 - 月份 - 日子 - 折扣券flag - 商品价钱
double calcPrice(int (*checkDate)(int, int), \
                 int monthInput,             \
                 int dateInput,              \
                 int flagCoupon,             \
                 double price) {
    // 1为双11,2为双12, 0不符合要求
    int flagDate = checkDate(monthInput, dateInput);
    if (flagDate) {
        if (flagDate == 1 && flagCoupon == 1) {
            price = price * 0.7 - 50;
        } else if (flagDate == 1 && flagCoupon == 0) {
            price = price * 0.7;
        } else if (flagDate == 2 && flagCoupon == 1) {
            price = price * 0.8 - 50;
        } else {
            price = price * 0.8;
        }
        // 有效日期,返回购入加钱
        return price;
    }
    // 无效日期,质问顾客: )
    return printf("Not today!!!!\n");
}



全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务