和Basic版相比,这个版本有以下几处不同点
这次采用的不是静态数组,而是动态数组,先定义一个数组“Dim buff()”,在运行过程中再根据需要扩展大小。
计算结果没有直接输出,而是写到文件,因为当字符串太长时,MsgBox的会丢失部分内容
难点:确定n!的位数是难点,ln(n!) 可用 斯特林逼近 来计算,ln(n!)= (n+0.5)ln(n)- n + 0.5*ln(2*pi)
请参考 http://mathworld.wolfram.com/StirlingsApproximation.html
下面为源代码
Dim n,i,j,c,t,len1
Dim buff()
Dim numstr
Const RAD=10000
Const PI=3.1415926535897932384626433832795
numstr= InputBox( "please input a numer n(n>1)", "calculate the n!", 1)
if numstr > "" and IsNumeric( numstr ) Then
n=CLng(numstr)
log_facn=(n+0.5)*Log(n)-n+0.5*Log(2*PI) 'log_facn=ln(n!)
ReDim buff(log_facn/Log(RAD)+1) 'Expand array size for store n!
buff(1)=1
len1=1
For i=1 to n
c=CLng(0)
For j= 1 to len1
t=CLng(buff(j))* CLng(i)+c
buff(j)=t MOD RAD
c=t \ RAD
Next
If c>0 Then
len1=len1+1
buff(len1)=c
End If
Next
'Caculation is completed, the following code for write the result to file
filename=".\" & CStr(n) & ".txt"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile(filename, True)
numstr=CStr(buff(len1))
For j=len1-1 to 1 step -1
t=CStr(buff(j))
If Len(t)<4 Then
numstr=numstr & String(4-Len(t),"0")
End If
numstr=numstr & t
If Len(numstr) > 76 Then
a.WriteLine(numstr)
numstr=""
End if
Next
If (Len(numstr)>0) Then
a.WriteLine(numstr)
End If
a.close
MsgBox "Result have been stored to file " & filename,0,"calculate n!"
Else
MsgBox "Invalid input"
End if
参考学习资料
1. VBScript 教程,可从VBScript http://download.pchome.net/development/reference/detail-11108.html
2. VB script 脚本语言.doc