added rationals
This commit is contained in:
parent
f66fdac8b4
commit
3c2e6a7175
21
src/Lesson3/Rational.sc
Normal file
21
src/Lesson3/Rational.sc
Normal file
@ -0,0 +1,21 @@
|
||||
class Rational(n: Int, d: Int) {
|
||||
def num = n
|
||||
def denom = d
|
||||
}
|
||||
|
||||
def add(x: Rational, y: Rational): Rational =
|
||||
new Rational(
|
||||
x.num * y.denom + x.denom * y.num,
|
||||
x.denom * y.denom
|
||||
)
|
||||
|
||||
def stringVersion(x: Rational) = x.num + "/" + x.denom
|
||||
|
||||
val r1 = new Rational(1, 2)
|
||||
r1.num
|
||||
r1.denom
|
||||
|
||||
val r2 = new Rational(3, 4)
|
||||
|
||||
val r3 = add(r1, r2)
|
||||
stringVersion(r3)
|
31
src/Lesson3/Rational2.sc
Normal file
31
src/Lesson3/Rational2.sc
Normal file
@ -0,0 +1,31 @@
|
||||
class Rational(n: Int, d: Int) {
|
||||
def num = n
|
||||
def denom = d
|
||||
|
||||
def add(that: Rational): Rational = new Rational(
|
||||
this.num * that.denom + this.denom * that.num,
|
||||
this.denom * that.denom
|
||||
)
|
||||
|
||||
def neg: Rational = new Rational(-num, denom)
|
||||
|
||||
def smallerThan(that: Rational): Boolean = this.num * that.denom < that.num * this.denom
|
||||
|
||||
def max(that: Rational): Rational = if (this.smallerThan(that)) that else this
|
||||
|
||||
override def toString = num + "/" + denom
|
||||
}
|
||||
|
||||
val r1 = new Rational(1, 3)
|
||||
val r2 = new Rational(2, 3)
|
||||
val r3 = r1.add(r2)
|
||||
|
||||
r3
|
||||
|
||||
r2.neg
|
||||
|
||||
r2.smallerThan(r1)
|
||||
r2.smallerThan(r3)
|
||||
|
||||
r2.max(r1)
|
||||
r2.max(r3)
|
Loading…
x
Reference in New Issue
Block a user