面试题答案
一键面试#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;
}
解释:
calculateDiscountedPrice
函数接收商品总价totalPrice
和是否为新用户的布尔值isNewUser
。- 通过
if - else
语句来判断总价范围,并根据是否为新用户来决定折扣。 - 在
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;
}
扩展说明:
- 定义了
UserLevel
枚举来表示不同的用户等级。 - 修改
calculateDiscountedPrice
函数,接收UserLevel
作为参数。 - 在总价大于等于200元时,使用
switch
语句根据不同的用户等级来确定折扣。这样代码结构更清晰,也方便继续添加新的用户等级和对应的折扣逻辑。