題目:實現一個簡單的“銀行賬戶”類
要求:
使用 元表 模擬面向對象。
支持以下功能:
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