实验 2 Scala 编程初级实践

一实验目的

二实验平台

三实验内容和要求

1、计算级数

 

 

 

2、模拟图形绘制

trait Drawable {
def draw(): Unit = println(this.toString)
}

case class Point(var x: Double, var y: Double) extends Drawable {
def shift(X: Double, Y: Double): Unit = {
x += X
y += Y
}
}

abstract class Shape(var location: Point) {
def moveTo(newLocation: Point): Unit = {
location = newLocation
}

def zoom(scale: Double): Unit
}

class Line(beginPoint: Point, var endPoint: Point) extends Shape(beginPoint) with Drawable {
override def draw(): Unit = {
println(s"Line:(${location.x},${location.y})--(${endPoint.x},${endPoint.y})")
}

override def moveTo(newLocation: Point): Unit = {
endPoint.shift(newLocation.x - location.x, newLocation.y - location.y)
location = newLocation
}

override def zoom(scale: Double): Unit = {
val midPoint = Point((endPoint.x + location.x) / 2, (endPoint.y + location.y) / 2)
location.x = midPoint.x + scale * (location.x - midPoint.x)
location.y = midPoint.y + scale * (location.y - midPoint.y)
endPoint.x = midPoint.x + scale * (endPoint.x - midPoint.x)
endPoint.y = midPoint.y + scale * (endPoint.y - midPoint.y)
}
}

class Circle(center: Point, var radius: Double) extends Shape(center) with Drawable {
override def draw(): Unit = {
println(s"Circle center:(${location.x},${location.y}),R=$radius")
}

override def zoom(scale: Double): Unit = {
radius = radius * scale
}
}

object MyDraw {
def main(args: Array[String]): Unit = {
val p = Point(10, 30)
p.draw()

val line1 = new Line(Point(0, 0), Point(20, 20))
line1.draw()
line1.moveTo(Point(5, 5))
line1.draw()
line1.zoom(2)
line1.draw()

val circle = new Circle(Point(10, 10), 5)
circle.draw()
circle.moveTo(Point(30, 20))
circle.draw()
circle.zoom(0.5)
circle.draw()
}
}

 

 

3、统计学生成绩

四实验报告

 

posted @ 2024-05-25 11:26  喝着农药吐泡泡o  阅读(7)  评论(0编辑  收藏  举报