IntelliJ中Kotlin的sign与floorDiv使用报错求助
解决Kotlin中向上取整除法的两类报错
报错1:Unresolved reference: floorDiv
floorDiv是Kotlin 1.3及以上版本才引入的Int扩展函数,若项目Kotlin版本低于1.3,就会触发该报错。解决途径:
- 升级Kotlin版本:
- 打开IntelliJ的
File → Project Structure → Modules - 选中目标模块,在
Kotlin SDK下拉菜单中选择1.3或更高版本 - 或在项目的
build.gradle(或build.gradle.kts)中指定版本,示例:plugins { id 'org.jetbrains.kotlin.jvm' version '1.9.20' }
- 打开IntelliJ的
- 手动实现floorDiv逻辑(无法升级版本时):
正整数场景下,floorDiv等价于普通整数除法this / other;若需支持正负整数,可按以下逻辑实现:fun Int.myFloorDiv(other: Int): Int { require(other != 0) { "Divisor cannot be zero" } return if ((this > 0 && other > 0) || (this < 0 && other < 0)) { this / other } else { (this - other + 1) / other } }
报错2:Type mismatch: inferred type is Int but Double was expected
你导入的kotlin.math.sign是针对Double/Float类型的函数,返回值为Double,但代码中的rem是Int类型,直接相加会引发类型不匹配。解决方式:
- 使用
Int自带的sign属性(返回值为Int类型:1、0、-1),无需导入kotlin.math.sign - 修正你的第一个代码示例:
fun main() { for(dividend in 1..10){ for(divisor in 1..5){ val rem = dividend % divisor // 正整数场景下,余数>0则加1实现向上取整 val result = dividend / divisor + if(rem > 0) 1 else 0 print("$result ") } println() } }
正确的向上取整除法扩展函数
适配Kotlin 1.3+版本
fun Int.ceilDiv(other: Int): Int { require(other != 0) { "Divisor cannot be zero" } val remainder = this.rem(other) return if (remainder == 0) { this.floorDiv(other) } else { this.floorDiv(other) + remainder.sign } }
适配低版本Kotlin(<1.3)
fun Int.ceilDiv(other: Int): Int { require(other != 0) { "Divisor cannot be zero" } val quotient = this / other val remainder = this % other return if (remainder == 0) { quotient } else { // 根据被除数和除数的符号判断是否需要调整商 quotient + if ((this > 0 && other > 0) || (this < 0 && other < 0)) 1 else -1 } }
内容的提问来源于stack exchange,提问作者Doragon
相关产品推荐
相关产品推荐

