2019年5月23日 星期四

Kotlin 高中程式練習題 a006: 一元二次方程式

Kotlin 高中程式練習題 a006: 一元二次方程式


求一元二次方程式 ax2+bx+c=0 的根
輸入說明
輸入三個整數 a, b, c

輸出說明
Two different roots x1=?? , x2=??
Two same roots x=??
No real root a+bi , a-bi

var a: Double =0.0
var b: Double =0.0
var c: Double =0.0

fun main(args: Array<String>) {
    println("ax^2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0")
    print("input a  b  c number =")
    val (a1,b1,c1) = readLine()!!.split(' ')
    a=a1.toDouble()
    b=b1.toDouble()
    c=c1.toDouble()

    val root1: Double
    val root2: Double
    val output: String

    val determinant = b * b - 4.0 * a * c

    // condition for real and different roots
    if (determinant > 0) {
        root1 = (-b + Math.sqrt(determinant)) / (2 * a)
        root2 = (-b - Math.sqrt(determinant)) / (2 * a)

        output = "root1 = %.2f and root2 = %.2f".format(root1, root2)
    }
    // Condition for real and equal roots
    else if (determinant == 0.0) {
        root2 = -b / (2 * a)
        root1 = root2

        output = "root1 = root2 = %.2f;".format(root1)
    }
    // If roots are not real
    else {
        val realPart = -b / (2 * a)
        val imaginaryPart = Math.sqrt(-determinant) / (2 * a)

        output = "root1 = %.2f+%.2fi and root2 = %.2f-%.2fi".format(realPart, imaginaryPart, realPart, imaginaryPart)
    }

    println(output)
}

輸出畫面
ax^2 + bx + c = 0, where a, b and c are real numbers and a ? 0
input a  b  c number =1 3 10
root1 = -1.50+2.78i and root2 = -1.50-2.78i


ax^2 + bx + c = 0, where a, b and c are real numbers and a ? 0
input a  b  c number =1 -3 -10
root1 = 5.00 and root2 = -2.00

ax^2 + bx + c = 0, where a, b and c are real numbers and a ? 0
input a  b  c number =1 -4 4
root1 = root2 = 2.00;


沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...