使用TypeScript编写一段程序模拟信用卡消费 信用卡账户上一般包含: 1、卡面余额(可取款提现、可消费) 2、透支额度(仅限消费) 要求传入一个消费金额amount,根据账户上卡面余额和透支额度输出不同情况下的消费明细
时间: 2024-09-19 09:15:59 浏览: 57
diamondhunt-scripts:我将分享https的脚本
在 TypeScript 中,我们可以创建一个更详细的信用卡类 `CreditCard` 来模拟上述需求,包括卡面余额、透支额度以及相应的消费逻辑。这里我们将消费分为三种情况:正常消费、透支消费和取款。以下是示例代码:
```typescript
class CreditCard {
private balance: number; // 卡面余额
private overdrawLimit: number; // 透支额度
private withdrawalLimit: number; // 取款限额
constructor(balance: number, overdrawLimit: number, withdrawalLimit: number) {
this.balance = balance;
this.overdrawLimit = overdrawLimit;
this.withdrawalLimit = withdrawalLimit;
}
public consume(amount: number): string {
if (amount <= this.balance) { // 正常消费
this.balance -= amount;
return `Consumed ${amount}. New balance: ${this.balance}`;
} else if (amount <= this.balance + this.overdrawLimit) { // 透支消费
const totalPenalty = this.calculateOverdraftPenalty(amount);
this.balance -= amount - totalPenalty;
return `Consumed ${amount} with a penalty of ${totalPenalty}. New balance: ${this.balance}`;
} else { // 取款或超过透支上限
return "Insufficient funds or exceeding overdraft limit.";
}
}
private calculateOverdraftPenalty(amount: number): number {
// 简化示例,通常透支费用按百分比计算
return amount * 0.05; // 假设5%的透支罚息
}
public withdraw(amount: number): string {
if (amount <= this.withdrawalLimit && amount <= this.balance) {
this.balance -= amount;
return `Withdrawn ${amount}. New balance: ${this.balance}`;
} else {
return "Withdrawal not allowed or insufficient funds.";
}
}
}
// 示例使用
let myCard = new CreditCard(1000, 500, 200);
console.log(myCard.consume(800)); // 输出消费明细
console.log(myCard.withdraw(200)); // 输出取款明细
```
这个 `CreditCard` 类可以提供详细的消费和取款信息,根据输入金额判断不同的消费行为。如果消费超出了透支额度,还会计算相应的透支罚息。
阅读全文