小数的循环节

 输入N/D的形式,其中N为分子,D为分母。

  如得出的结果小数部分存在循环,就用括号括起来 ,如1/3=0.(3);22/5=4.4 ;1/7=(142857)

Function xunhuan(ByVal N As Long, ByVal D As Long) As String '请依次输入N/D得形式,其中N为分子,D为分母

If N Mod D = 0 Then '整除
xunhuan = N & "÷" & D & "=" & N / D
Exit Function
Else


Dim digit() As String, flag() As Long, temp As Double, temp2 As Long, i As Long, K As Integer
ReDim digit(1 To D + Len(CStr(D))) '定义最长不重复位数
ReDim flag(D) '0-D 每位数字出现于小数点后的位置
xunhuan = N & "÷" & D & "=" & Int(N / D) & "."

temp = N Mod D '取余

i = 2
Do While i <= D + Len(CStr(D)) '循环所有可能

If temp = 0 Then '除尽了
ReDim Preserve digit(1 To i) '前i位
xunhuan = xunhuan & Join(digit, "")
Exit Function
End If


If flag(temp) > 1 Then '重复出现
digit(flag(temp)) = "(" & digit(flag(temp)) 'flag(temp)指该数字第一次出现的位置,添加左括号
ReDim Preserve digit(1 To i - 1)
xunhuan = xunhuan & Join(digit, "") & ")" '添加右括号
Exit Function
Else
flag(temp) = i '赋值
End If
'以下三行模拟除法运算,实现高精度除法
temp = temp * 10
digit(i) = Int(temp / D) Mod 10
temp = temp - Int(temp / D) * D

i = i + 1

Loop

End If
End Function

Private Sub Command1_Click()
Dim t As Single
Dim i As Long, x(1 To 10000) As String
t = Timer
For i = 1 To 10000
x(i) = xunhuan(i, 65535)
Next
Randomize
i = Int(10000 * Rnd + 1)
MsgBox "计算完毕!列举其中任意一个:" & vbCrLf & x(i), vbInformation, "用时" & Timer - t & "秒"
End Sub

你可能感兴趣的:(循环)