Search code examples
javakotlinmathareatriangle

kotlin does wrong equations. it does not calculate correctly


fun main(args: Array<String>) {
    val pie = 22/7
    println("Enter a number for triangle area")
    val input = readLine()?: ""
    val a = input.toInt() * input.toInt()  * pie
    println(a)
}

here when I input 6 it should give us 113.142857143 or 113.14

Instead, it gives 108

output

and with javascript it's fine

js output


Solution

  • It treats the pie as an integer. After rounding the pie will become 3, so 6 * 3 * 3 is 108.

    There are numbers of ways to solve this but I recommend using BigDecimal to calculate decimals.

    fun main(args: Array<String>) {
        val pie = BigDecimal.valueOf(Math.PI) // Either Math.PI or 22/7, one is 3.1415 another is 3.1428
        println("Enter a number for triangle area")
        val input = readLine()?: "0" // PLEASE DO INPUT VALIDATION HERE
        val inputDecimal = BigDecimal(input)
        val a = inputDecimal.multiply(inputDecimal).multiply(pie)
        println(a)
    }