我正在尝试使用Heron's formula实现一个计算欧几里得空间中三角形面积的函数。不幸的是,我不知道如何外包部分函数,然后将它们作为参数传递。
这就是我到目前为止所做的:
import scala.math._
def sqr(a:Double) = a*a
def length(x1:Double,y1:Double,x2:Double,y2:Double)=sqrt(sqr(x2-x1)+sqr(y2-y1))
val a = length(x1,y1,x2,y2)
val b = length(x2,y2,x3,y3)
val c = length(x3,y3,x1,y1)
val u = 0.5*a*b*c
heron(x1:Double,y1:Double,x2:Double,y2:Double,x3:Double,y3:Double) = sqrt(u*(u-a)*(u-b)*(u-c))
这显然不起作用,但我希望你能得到我想做的事。
答案 0 :(得分:2)
我想你只想在你的函数中定义那些中间值:
// btw, using scala.math.power you can write 'power(a, 2)'
def sqr(a: Double): Double = a * a
def length(
x1: Double, y1: Double,
x2: Double, y2: Double
): Double = sqrt(
sqr(x2 - x1) +
sqr(y2 - y1)
)
def heron(
x1: Double, y1: Double,
x2: Double, y2: Double,
x3: Double, y3: Double
): Double = {
val a = length(x1, y1, x2, y2)
val b = length(x2, y2, x3, y3)
val c = length(x3, y3, x1, y1)
val u = 0.5 * a * b * c
sqrt(u * (u - a) * (u - b) * (u - c))
}
我还建议你在代码中添加更多空格,使其更具可读性。