Sample code:
Type Fraction
Field N ;Numerator
Field D ;Denominator
End Type
a.Fraction = New Fraction
b.Fraction = New Fraction
c.Fraction = New Fraction
a\N = 1: a\D = 4 ;1/4
b\N = 10: b\D = 3 ;10/3
c = Add(a, b)
Print "1/4 + 10/3 = " + c\N + "/" + c\D
a\N = 1: a\D = 11 ;1/11
b\N = 120: b\D = 11 ;120/11
c = Add(a, b)
Print "1/11 + 120/11 = " + c\N + "/" + c\D
WaitKey
Delete Each Fraction
End
Function Add.Fraction(num1.Fraction, num2.Fraction)
If sum.Fraction = Null Then sum.Fraction = New fraction
sum\N = num1\N * num2\D + num2\N * num1\D
sum\D = num1\D * num2\D
sum = Simplify(sum)
Return sum
End Function
Function Simplify.Fraction(num.Fraction)
Repeat
foundDivisor = False
For attempt = 1 To 5
Select attempt
Case 1
divisor = 2
Case 2
divisor = 3
Case 3
divisor = 5
Case 4
divisor = 7
Case 5
divisor = 11
;Case 6
;continue on for as many prime numbers as you want...
End Select
If num\N Mod divisor = 0 And num\D Mod divisor = 0
num\N = num\N / divisor
num\D = num\D / divisor
foundDivisor = True
Exit
EndIf
Next
Until foundDivisor = False
Return num
End Function You owe me ;) ...
You know, when I was in sixth grade and was learing how to handle fractions, I thought, OH GOD, this really sucks!
But when I later got into algebra and trigonometry, I realized that using fractions was SO MUCH BETTER than dealing with inaccurate decimals. For instance, a number like 1/3 is perfectly represented as a fraction, but can never be perfectly represented as a decimal. That is when I truly realized how valuable fractions were.
|