Public Class simplefraction
' Methods
Public Sub New(ByVal num As Integer, ByVal deno As Integer)
Me._numerator = num
Me._denominator = deno
End Sub
Public Function Display() As String
Me.Simplifying
Return String.Format("{0}/{1}", Me._numerator, Me._denominator )
End Function
Public Shared Operator +(ByVal a As simplefraction, ByVal b As simplefraction) As simplefraction
Return New simplefraction(((a._numerator * b._denominator ) + (b._numerator * a._denominator )), (a._denominator * b._denominator ))
End Operator
Public Shared Operator /(ByVal a As simplefraction, ByVal b As simplefraction) As simplefraction
Return New simplefraction((a._numerator * b._denominator ), (a._denominator * b._numerator))
End Operator
Public Shared Operator *(ByVal a As simplefraction, ByVal b As simplefraction) As simplefraction
Return New simplefraction((a._numerator * b._numerator), (a._denominator * b._denominator ))
End Operator
Public Shared Operator -(ByVal a As simplefraction, ByVal b As simplefraction) As simplefraction
Return New simplefraction(((a._numerator * b._denominator ) - (b._numerator * a._denominator )), (a._denominator * b._denominator ))
End Operator
Private Sub Simplifying()
Dim turn As Integer = 0
Dim minus As Boolean = (Me._numerator < 0)
Me._numerator = Math.Abs(Me._numerator)
turn = Math.Min(Me._numerator, Me._denominator )
Do While (turn > 1)
If (((Me._numerator Mod turn) = 0) AndAlso ((Me._denominator Mod turn) = 0)) Then
Me._numerator = (Me._numerator / turn)
Me._denominator = (Me._denominator / turn)
Else
turn -= 1
End If
Loop
If minus Then
Me._numerator = (-1 * Me._numerator)
End If
End Sub
' Properties
Public ReadOnly Property Denominator As String
Get
Return Me._denominator .ToString
End Get
End Property
Public ReadOnly Property Numerator As String
Get
Return Me._numerator.ToString
End Get
End Property
' Fields
Private _denominator As Integer
Private _numerator As Integer
End Class
调用
Dim _a As String = "1/2"
Dim _b As String = "1/4"
Dim arr() As String = _a.Split("/")
Dim brr() As String = _b.Split("/")
Dim a As new simplefraction(val(arr(0)), val(arr(1)))
Dim b As new simplefraction(val(brr(0)), val(brr(1)))
Dim c As simplefraction = a + b
msgbox(c.Display)
c = a - b
msgbox(c.Display)
c = a * b
msgbox(c.Display)
c = a / b
msgbox(c.Display)