从Scala

时间:2017-03-16 07:03:16

标签: scala extract equation quadratic

我正在尝试编写一个程序,可以使用Scala找到二次方程的根。输入应该是ax ^ 2 + bx + c形式的二次方程(例如:5x ^ 2 + 2x + 3)作为字符串。

我设法对根进行编码,但是无法从输入中提取系数。这是我到目前为止用于提取系数的代码:

def getCoef(poly: String) = {
  var aT: String = ""
  var bT: String = ""
  var cT: String = ""
  var x: Int = 2
  for (i <- poly.length - 1 to 0) {
    val t: String = poly(i).toString
    if (x == 2) {
      if (t forall Character.isDigit) aT = aT + t(i)
      else if (t == "^") {i = i + 1; x = 1}
    }
    else if (x == 1) {
      if (t forall Character.isDigit) bT = bT + t(i)
      else if (t == "+" || t == "-") x = 0
    }
    else if (x == 0) {
      if (t forall Character.isDigit) cT = cT + t(i)
    }
  val a: Int = aT.toInt
  val b: Int = bT.toInt
  val c: Int = cT.toInt
  (a, b, c)
  }
}

1 个答案:

答案 0 :(得分:0)

使用正则表达式的简单解决方案:

def getCoef(poly: String) = {
  val polyPattern = """(\d+)x\^2\+(\d+)x\+(\d+)""".r
  val matcher = polyPattern.findFirstMatchIn(poly).get
  (matcher.group(1).toInt, matcher.group(2).toInt, matcher.group(3).toInt)
}

不处理所有情况(例如:减号)并且如果输入与模式不匹配则抛出错误,但它应该让你去。