当前位置: 首页 > news >正文

【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 = 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
http://www.dtcms.com/a/326041.html

相关文章:

  • 从零构建自定义Spring Boot Starter:打造你的专属开箱即用组件
  • 爬虫与数据分析入门:从中国大学排名爬取到数据可视化全流程
  • Go语言构建高性能AI分析网关:原理与实战
  • 设计模式笔记_结构型_组合模式
  • React(四):事件总线、setState的细节、PureComponent、ref
  • Jenkins 搭建鸿蒙打包
  • 【k8s】k8s中的几个概念性问题
  • day48 力扣739. 每日温度 力扣496.下一个更大元素 I 力扣503.下一个更大元素II
  • 轻量级解决方案:如何高效处理Word转PDF?
  • k8s的calico是什么作用,举例一下
  • 【2025最新版】PDF24 Creator,PDF编辑,合并分割,格式转换全能工具箱,本地离线版本,完全免费!
  • 【C语言强化训练16天】--从基础到进阶的蜕变之旅:Day1
  • 【12-激活函数】
  • 【PRML】分类
  • 普通大学本科生如何入门强化学习?
  • 算法73. 矩阵置零
  • MySQL权限管理和MySQL备份
  • 银行客户经营:用企业微信精准破解触达断层、效率瓶颈、数据孤岛三个痛点
  • GPT-5 全面解析与最佳实践指南
  • 容器 K8S Docker Kata 学习(一)
  • idea三个环境变量设置
  • Spring Boot Excel数据导入数据库实现详解
  • Spring-Security-5.7.11升级6.5.2
  • Socket(套接字)网络编程
  • Scala异步任务编排与弹性容错机制
  • [特殊字符]走进标杆工厂参观研学| 破茧成蝶的感悟之旅
  • Spring Boot 中 @Transactional 解析
  • Spring Boot启动事件详解:类型、监听与实战应用
  • PyCharm(2025.1.3.1)绑定 Conda 环境
  • SoftCnKiller:绿色小巧,流氓软件一键扫描!