当前位置:网站首页>Kotlin算法入门求自由落体
Kotlin算法入门求自由落体
2022-08-11 08:01:00 【易庞宙】
/* 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下, 求它在第10次落地时,共经过多少米?第10次反弹多高 这里用BigDecimal避免精度丢失 */ class FreeFallingBody { fun tradition() { //传统算法 循环10次计算这里用BigDecimal避免精度丢失 val distance = BigDecimal(100.0) var height = BigDecimal(100.0) var result: BigDecimal? = null val percentage = BigDecimal(2.0) for (i in 0..9) { height = height.divide(percentage) if (result == null) result = distance.add(height) else result = result.add(height) //System.out.println("distance" + result); } println(result) } /** * 这里用BigDecimal避免精度丢失 * 以1为次数起点正向递归求第n次后自由落体后小球运动了多少距离 * 自定义求第n次后自由落体后小球运动了多少距离 * 以及逆向求第k次前的第n次之间自由落体后小球运动了多少距离 * 递归逆向求运动距离时候distance第一次运动距离为 0 */ fun diyFreeFallingBody(fallingTimes: Int, thisTimes: Int, height: BigDecimal, percentageHeight: BigDecimal, distance: BigDecimal): BigDecimal { var distance = distance /**所求落体次数相同则直接返回高度 */ if (thisTimes == fallingTimes) return distance.add(height.divide(percentageHeight)) else if (thisTimes < fallingTimes) { /**反复正向递归求下一次自由落体高度 */ if (thisTimes == 1) distance = height val nextHeight = height.divide(percentageHeight) return diyFreeFallingBody(fallingTimes, thisTimes + 1, nextHeight, percentageHeight, distance.add(nextHeight)) } else if (thisTimes > fallingTimes + 1) { /**反复逆向递归求下一次自由落体高度 */ val lastHeight = height.multiply(percentageHeight) if (distance.toInt() == 0) distance = height println("distance$distance") return diyFreeFallingBody(fallingTimes, thisTimes - 1, lastHeight, percentageHeight, distance.add(lastHeight)) } else if (thisTimes == fallingTimes + 1) { return distanKotlince.add(height.multiply(percentageHeight)) } return BigDecimal(0) } }
边栏推荐
猜你喜欢
随机推荐
无服务器+域名也能搭建个人博客?真的,而且很快
go 操作MySQL之mysql包
Interaction of Pico neo3 in Unity
项目2-年收入判断
用 Antlr 重构脚本解释器
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
1.1-回归
1071 Small Gamble (15 points)
高德能力API
1036 Programming with Obama (15 points)
The easiest trick to support quick renaming of various files
8、Mip-NeRF
麒麟V10系统打包Qt免安装包程序
klayout--导出版图为gds文件
关于Excel实现分组求和最全文档
C Primer Plus(6) 中文版 第1章 初识C语言 1.1 C语言的起源 1.2 选择C语言的理由 1.3 C语言的应用范围
excel 透视表 值显示内容 不显示计数
3.1-Classification-probabilistic generative model
2021-08-11 For loop combined with multi-threaded asynchronous query and collect results
The growth path of a 40W test engineer with an annual salary, which stage are you in?