Quadratic equation in Scala
Example for versions
Scala 2.7.7-final,
Scala 2.8.0-final
This example expands the interactive one with variables input.
import java.io.{BufferedReader, InputStreamReader}
object Main {
def main(args: Array[String]) {
var stdin = new BufferedReader(new InputStreamReader(System.in));
var A = augmentString(stdin.readLine()).toInt;
var B = augmentString(stdin.readLine()).toInt;
var C = augmentString(stdin.readLine()).toInt;
solve(A,B,C);
}
def output(real: Double, imag: Double): String =
if (imag == 0) ""+real
else "("+real+","+imag+")"
def solve(A: Int, B: Int, C: Int)
{ if (A == 0) print("Not a quadratic equation.")
else
{ def D = B*B - 4*A*C;
if (D == 0) print("x = "+output(-B/2.0/A, 0));
else if (D > 0)
print("x1 = "+output((-B+Math.sqrt(D))/2.0/A, 0)+"\nx2 = "+output((-B-Math.sqrt(D))/2.0/A, 0));
else print("x1 = "+output(-B/2/A, Math.sqrt(-D)/2.0/A)+"\nx2 = "+output(-B/2/A, -Math.sqrt(-D)/2.0/A));
}
}
}
Comments
]]>blog comments powered by Disqus
]]>