深入解析:【Lua】题目小练9

题目:实现一个简单的“银行账户”类

要求:

  1. 使用 元表 模拟面向对象。

  2. 支撑以下效果:

    • Account:new(owner, balance) 创建账户(初始余额可选,默认为 0)。

    • deposit(amount) 存款(不能为负数)。

    • withdraw(amount) 取款(余额不足时拒绝取款)。

    • getBalance() 查看余额。

  3. 所有金额操作必须保留两位小数(比如 100.567 存款后变成 100.57)。

  4. 加分项:实现两个账户之间的转账方法 transfer(toAccount, amount)

local Account = {}
Account.__index = Account
local function RoundBalance(balance)
return math.floor(balance * 100 + 0.5) / 100
end
function Account:new(owner, balance)
local obj = {
owner = owner or "Alice",
balance = (type(balance) == "number") and balance > 0 and RoundBalance(balance) or 0
}
setmetatable(obj, Account)
return obj
end
function Account:deposit(amount)
if type(amount) == "number" and amount >= 0 then
self.balance = RoundBalance(self.balance + amount)
print(tostring(self.owner) .. "存款")
end
end
function Account:withdraw(amount)
if type(amount) == "number" and amount >= 0 and self.balance >= amount then
self.balance = RoundBalance(self.balance - amount)
print(tostring(self.owner) .. "取款")
end
end
function Account:getBalance()
return self.balance
end
function Account:transfer(toAccount, amount)
if type(toAccount) == "table" and type(amount) == "number" and amount >= 0 and self.balance >= amount then
self.balance = RoundBalance(self.balance - amount)
toAccount.balance = RoundBalance(toAccount.balance + amount)
print("成功转账给" .. tostring(toAccount.owner) .. ":".. amount)
end
end
local a = Account:new("Alice", 100)
local b = Account:new("Bob")
a:deposit(50.456)       -- Alice 存款
a:withdraw(30)          -- Alice 取款
a:transfer(b, 50)       -- 转账给 Bob
print("Alice 余额:", a:getBalance()) -- 70.46
print("Bob 余额:", b:getBalance())   -- 50.00
posted @ 2025-08-14 13:45  yjbjingcha  阅读(12)  评论(0)    收藏  举报