Can anyone tell me why my arithmetic code isn't working? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can anyone tell me why my arithmetic code isn't working?

//ax + b = c //x = (c-b)/a fun main(args: Array<String>) { var equ = readLine()!!.toString() var a: Int = equ.get(0).toInt() var b: Double = equ.get(3).toDouble() var c: Double = equ.get(5).toDouble() println("X is equal to ${(c - b) / a}")

26th Jun 2020, 8:52 PM
Phillipa Austin-Seymour
Phillipa Austin-Seymour - avatar
4 Answers
+ 7
If you space separate your input, you could make a list of them. Data entered to prompt: 3 2.1 4.5 val equ = readLine()!!.split(" ") makes equ a listOf("3", "2.1", "4.5") val a = equ[0].toInt() val b = equ[1].toDouble() val c = equ[2].toDouble() gets the numbers from the strings. Since you are not modifying your variables, they should be declared val instead of var.
27th Jun 2020, 5:14 AM
John Wells
John Wells - avatar
+ 2
In kotlin, when converting Char to Int (using toInt()), the, the character value is returned, not the number it represents... So for 1, this would be 49... You could first convert your char to string, and then go on converting to Int... This would meet your expectation... equ.get(0).toString().toInt()... Further, I think you want to access index 0, 2, 4... Not 0, 3, 5 ??
26th Jun 2020, 9:30 PM
G B
G B - avatar
+ 1
Thank you so much!
27th Jun 2020, 9:06 AM
Phillipa Austin-Seymour
Phillipa Austin-Seymour - avatar
0
Obviously the goInt() and toDouble() functions work different from your (and my) expectations, but I'm not familiar with Kotlin, so I can't help you. But maybe this hint helps you to find the proper solution...
26th Jun 2020, 9:16 PM
Sandra Meyer
Sandra Meyer - avatar