从在 Scala 中作为字符串输入的二项式表达式中提取系数
Extract coefficients from binomial expression entered as a string in Scala
我正在尝试编写一个可以使用 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)
}
}
使用正则表达式的简单解决方案:
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)
}
不处理所有情况(例如:减号),如果输入与模式不匹配则抛出错误,但它应该让你继续。
我正在尝试编写一个可以使用 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)
}
}
使用正则表达式的简单解决方案:
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)
}
不处理所有情况(例如:减号),如果输入与模式不匹配则抛出错误,但它应该让你继续。