added rationals

This commit is contained in:
2025-03-04 14:22:10 +01:00
parent f66fdac8b4
commit 3c2e6a7175
2 changed files with 52 additions and 0 deletions

21
src/Lesson3/Rational.sc Normal file
View 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)