【Lua】题目小练9
题目:实现一个简单的“银行账户”类
要求:
使用 元表 模拟面向对象。
支持以下功能:
Account:new(owner, balance)
创建账户(初始余额可选,默认为 0)。
deposit(amount)
存款(不能为负数)。
withdraw(amount)
取款(余额不足时拒绝取款)。
getBalance()
查看余额。所有金额操作必须保留两位小数(比如 100.567 存款后变成 100.57)。
加分项:实现两个账户之间的转账方法
transfer(toAccount, amount)
。local Account = {} Account.__index = Accountlocal function RoundBalance(balance)return math.floor(balance * 100 + 0.5) / 100 endfunction 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 endfunction Account:deposit(amount)if type(amount) == "number" and amount >= 0 thenself.balance = RoundBalance(self.balance + amount)print(tostring(self.owner) .. "存款")end endfunction Account:withdraw(amount)if type(amount) == "number" and amount >= 0 and self.balance >= amount thenself.balance = RoundBalance(self.balance - amount)print(tostring(self.owner) .. "取款")end endfunction Account:getBalance()return self.balance endfunction 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 endlocal 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