下面的代码,只支持一个分数的加减操作。
如果要实现楼主想要的分数计算,就必须自己去实现eval()函数,对表达式进行提取,分析,运算。比较麻烦......涉及递归,操作符比较。
也就是说,让电脑按照人的顺序去运算,很费精力……楼主请高手帮忙哈。
Dim data As String = "10/5+(5-2/10)+4"
Dim catchs As New System.Text.RegularExpressions.Regex("[\+\-\*/\(\)]*\d+")
Dim mc As System.Text.RegularExpressions.MatchCollection = catchs.Matches(data)
Dim maxfm As Double = 1
Dim nums(mc.count - 1) As String
Dim fzs(mc.count - 1) As String
catchs = New System.Text.RegularExpressions.Regex("^[\+\-\*/\(]+")
Dim mc0 As System.Text.RegularExpressions.MatchCollection = catchs.Matches(mc(0).Value)
If mc0.Count = 0 Then
nums(0) = "+" & mc(0).Value
Else
nums(0) = mc(0).Value
End If
Dim m, n, r As Double
For i As Integer = 1 To mc.Count - 1
nums(i) = mc(i).Value
If nums(i).IndexOf("/") <> -1 Then
catchs = New System.Text.RegularExpressions.Regex("\d+")
Dim mc2 As System.Text.RegularExpressions.MatchCollection = catchs.Matches(nums(i))
Dim right As Integer = mc2(0).Value
'求最小公倍数
If right > maxfm Then
m = right
n = maxfm
Else
m = maxfm
n = right
End If
Do
r = m Mod n
If r = 0 Then Exit Do
m = n
n = r
Loop
maxfm = maxfm * right / n
End If
Next
Dim Index As Integer = 0
For i As Integer = 0 To nums.Length - 1
catchs = New System.Text.RegularExpressions.Regex("[^\d]+")
Dim mc2 As System.Text.RegularExpressions.MatchCollection = catchs.Matches(nums(i))
Dim left As String = mc2(0).Value
catchs = New System.Text.RegularExpressions.Regex("\d+")
Dim mc3 As System.Text.RegularExpressions.MatchCollection = catchs.Matches(nums(i))
Dim right As Integer = mc3(0).Value
If nums(i).IndexOf("/") = -1 Then '如果不是分母
fzs(Index) = left & right * maxfm
Index = Index + 1
Else
catchs = New System.Text.RegularExpressions.Regex("[^\d]+")
Dim mc4 As System.Text.RegularExpressions.MatchCollection = catchs.Matches(fzs(Index - 1))
Dim last_left As String = mc4(0).Value
catchs = New System.Text.RegularExpressions.Regex("\d+")
Dim mc5 As System.Text.RegularExpressions.MatchCollection = catchs.Matches(fzs(Index - 1))
Dim last_right As Double = mc5(0).Value
fzs(Index - 1) = last_left & last_right / right
End If
Next
Dim fz As String = ""
For i As Integer = 0 To fzs.Length - 1
fz = fz & fzs(i)
Next
Dim num As String = ""
For i As Integer = 0 To nums.Length - 1
num = num & nums(i)
Next
fz = fz & data.SubString(num.Length - 1)
fz = eval(fz)
'约分
If fz > maxfm Then
m = fz
n = maxfm
Else
m = maxfm
n = fz
End If
Do
r = m Mod n
If r = 0 Then Exit Do
m = n
n = r
Loop
fz = fz / n
Dim fm As Integer = maxfm / n
Dim result As String = fz & "/" & fm
Output.Show(result)
[此贴子已经被作者于2012-9-30 19:38:04编辑过]