You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IntelliJ中Kotlin的sign与floorDiv使用报错求助

解决Kotlin中向上取整除法的两类报错

报错1:Unresolved reference: floorDiv

floorDiv是Kotlin 1.3及以上版本才引入的Int扩展函数,若项目Kotlin版本低于1.3,就会触发该报错。解决途径:

  • 升级Kotlin版本:
    1. 打开IntelliJ的File → Project Structure → Modules
    2. 选中目标模块,在Kotlin SDK下拉菜单中选择1.3或更高版本
    3. 或在项目的build.gradle(或build.gradle.kts)中指定版本,示例:
      plugins {
          id 'org.jetbrains.kotlin.jvm' version '1.9.20'
      }
      
  • 手动实现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 14:06:12