MST

星途 面试题库

面试题:Objective-C条件语句在复杂业务逻辑中的优化运用

在一个Objective-C的电商应用程序中,有如下业务逻辑:用户购买商品时,若商品总价小于100元且用户是新用户(通过一个布尔值标识),则享受9折优惠;若商品总价大于等于100元且小于200元,无论新老用户都享受85折优惠;若商品总价大于等于200元,新用户享受8折优惠,老用户享受82折优惠。请使用Objective-C的条件语句(if - else、switch等你认为合适的)设计并实现这个折扣计算功能,要求代码结构清晰,具备良好的扩展性,例如未来可能新增不同用户等级对应不同折扣的情况。
21.6万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
#import <Foundation/Foundation.h>

// 计算折扣价格的函数
CGFloat calculateDiscountedPrice(CGFloat totalPrice, BOOL isNewUser) {
    CGFloat discount = 1.0;
    if (totalPrice < 100) {
        if (isNewUser) {
            discount = 0.9;
        }
    } else if (totalPrice < 200) {
        discount = 0.85;
    } else {
        if (isNewUser) {
            discount = 0.8;
        } else {
            discount = 0.82;
        }
    }
    return totalPrice * discount;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        CGFloat totalPrice = 150; // 假设商品总价
        BOOL isNewUser = YES; // 假设是新用户
        CGFloat discountedPrice = calculateDiscountedPrice(totalPrice, isNewUser);
        NSLog(@"折扣后的价格是: %.2f", discountedPrice);
    }
    return 0;
}

解释:

  1. calculateDiscountedPrice 函数接收商品总价 totalPrice 和是否为新用户的布尔值 isNewUser
  2. 通过 if - else 语句来判断总价范围,并根据是否为新用户来决定折扣。
  3. main 函数中,演示了如何调用这个函数并输出折扣后的价格。

如果未来需要新增不同用户等级对应不同折扣的情况,可以考虑使用以下方式扩展:

// 用户等级枚举
typedef NS_ENUM(NSUInteger, UserLevel) {
    UserLevelNew = 0,
    UserLevelRegular,
    UserLevelVIP,
    // 可以继续添加更多等级
};

// 计算折扣价格的函数(扩展后)
CGFloat calculateDiscountedPrice(CGFloat totalPrice, UserLevel userLevel) {
    CGFloat discount = 1.0;
    if (totalPrice < 100) {
        if (userLevel == UserLevelNew) {
            discount = 0.9;
        }
    } else if (totalPrice < 200) {
        discount = 0.85;
    } else {
        switch (userLevel) {
            case UserLevelNew:
                discount = 0.8;
                break;
            case UserLevelRegular:
                discount = 0.82;
                break;
            case UserLevelVIP:
                discount = 0.75; // 假设VIP折扣
                break;
            default:
                break;
        }
    }
    return totalPrice * discount;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        CGFloat totalPrice = 250; // 假设商品总价
        UserLevel userLevel = UserLevelVIP; // 假设用户等级为VIP
        CGFloat discountedPrice = calculateDiscountedPrice(totalPrice, userLevel);
        NSLog(@"折扣后的价格是: %.2f", discountedPrice);
    }
    return 0;
}

扩展说明:

  1. 定义了 UserLevel 枚举来表示不同的用户等级。
  2. 修改 calculateDiscountedPrice 函数,接收 UserLevel 作为参数。
  3. 在总价大于等于200元时,使用 switch 语句根据不同的用户等级来确定折扣。这样代码结构更清晰,也方便继续添加新的用户等级和对应的折扣逻辑。