Home > Enterprise >  Hypotenuse of triangle Kotlin
Hypotenuse of triangle Kotlin

Time:10-19

Okay, pretty sure I got my formula right... don't think I quite understand how to call on methods, howcome mine isn't working?

    fun main() {
    println("Enter Width of the triangle")
    readln()
    println("Enter Height of the triangle")
    ComputeMethods().hypotenuse(readln().toDouble())
}

 class ComputeMethods(){
fun hypotenuse(width: Int, height: Int) {
    val triangle = width.toDouble().pow(2)   height.toDouble().pow(2)
    val formula = "$triangle"
    println(formula)
    }
}

CodePudding user response:

Your hypotenuse function has two arguments of type Int. You are only giving it one, and also of the wrong type (Double). Also, the result of your first readln is not stored anywhere. To solve it you can do:

fun main() {
    println("Enter Width of the triangle")
    val width: Int = readln().toInt()
    println("Enter Height of the triangle")
    val height: Int = readln().toInt()
    ComputeMethods().hypotenuse(width, height)
}

PS: to get the hypotenuse you would also need to take the square root of that result

CodePudding user response:

@Gilli, Here is the working code example for triangle formula, You have to pass input arguments in space separated format (2.0 3.0), You can interact with the link given https://pl.kotl.in/mq-8jgVRy in order to run the program on kotlin playground.

import kotlin.math.pow

fun main(args: Array<String>) {
    println("Enter Width of the triangle")
    val width = args[0].toDouble()
    println("Enter Height of the triangle")
    val height = args[1].toDouble()
    ComputeMethods().hypotenuse(width, height)
}

class ComputeMethods(){
fun hypotenuse(width: Double, height: Double) {
    val triangle = width.pow(2)   height.pow(2)
    val formula = "$triangle"
    println(formula)
    }
}
  • Related