Function Friction(Fri As Single) As String
Const MAX = 0.01
Dim i As Integer
Dim str As String
i = 1
While Abs((i / Fri) - Round((i / Fri), 0)) > MAX
i = i + 1
Wend
str = i & "/" & Round(i / Fri)
Friction = str
End Function
Private Sub Command1_Click()
MsgBox Friction(0.6666666)
End Sub
呀,我那段代码不能对付比如好像大于1的分数阿.那位大人帮忙该下.谢谢~
------------------
可以的,稍做修改:
Function Friction(Fri As Single, Optional digit As Integer = 2) As String
Dim i As Integer
Dim str As String
i = 1
While Abs((i / Fri) - Round((i / Fri), 0)) > 10 ^ (-digit)
i = i + 1
Wend
str = i & "/" & Round(i / Fri)
Friction = str
End Function
Private Sub Form_Load()
MsgBox Friction(3.14159, 2) & vbCrLf & Friction(3.14159, 4)'返回PI的疏率和密率
End Sub
seu31199113(Tony)寫的 ﹐高手
////////////////////////////////////////////
谢谢楼主给我灵感,我刚学VB一个星期!
=======
测试过了:str = Friction(0.142857142857) 结果是: 1/7
=======
Public Function Friction(Fri As Single) As String
Const MAX = 0.01
Dim i As Integer
Dim str As String
i = 1
While Abs((i / Fri) - Round((i / Fri), 0)) > MAX
i = i + 1
Wend
str = i & "/" & Round(i / Fri)
Friction = str
Option Explicit
Private Function Test(a As Single) As String
Dim strTmp As String
Dim strTmp1 As String
Dim intTmp As Integer
Dim intA As Integer
Dim intB As Integer
Dim intC As Integer
strTmp = Str(a)
strTmp1 = Left(strTmp, InStr(1, strTmp, ".") - 1)
strTmp = Right(strTmp, Len(strTmp) - InStr(1, strTmp, "."))
intA = Val(strTmp)
intB = 10 ^ Len(strTmp)
intC = G_cd(intA, intB)
If strTmp1 <> " " Then Test = strTmp1 & " + "
Test = Test & intA / intC & "/" & intB / intC
End Function
Private Function G_cd(ByVal a As Integer, ByVal b As Integer) As Integer
If a = 0 Then
G_cd = b
End If
If b = 0 Then
G_cd = a
End If
If a > b Then
Swap a, b
End If
Dim c As Integer
Do
c = a Mod b
a = b
b = c
DoEvents
Loop While c > 0
G_cd = a
End Function
Private Sub Swap(a As Integer, b As Integer)
Dim c As Integer
c = a
a = b
b = c
End Sub