返回平方数而非阶乘的阶乘函数



我的代码哪里错了?它返回任何数字的平方:

Sub factorial()
Dim x As Long, i As Integer, fact As Long
x = InputBox("enter the integer")
For i = 1 To x
fact = i * x
Next i
MsgBox fact
End Sub 

练习循环和If语句

Option Explicit
' If you are practicing (loops) then:
Sub factorial()
Dim x As Long, i As Long, fct As Double
x = InputBox("enter the integer")
If x >= 0 And x <= 170 Then
fct = 1
If x > 1 Then
For i = 2 To x
fct = fct * i
Next i
End If
MsgBox fct
Else
MsgBox "Next time enter a number between 0 and 170."
Exit Sub
End If
End Sub
' ...if not, just use Fact
Sub factorialExcel()
Dim x As Long
x = InputBox("enter the integer")
If x >= 0 And x <= 170 Then
MsgBox Application.WorksheetFunction.Fact(x)
Else
MsgBox "Next time enter a number between 0 and 170."
Exit Sub
End If
End Sub

一个错误是fact在循环中使用之前需要用fact=1初始化。然后在循环内部,结果应该乘以迭代次数,如fact = fact * i中所示。最后,为了确保获得尽可能高的范围,请使用LongLong类型(在VB7及以上版本中可用(,它是一个64位整数。哦,别忘了将InputBox返回的文本转换为数字类型。

Sub factorial()
Dim x As Long, i As Long, fact As LongLong
x = CLng(InputBox("enter the integer"))
fact = 1
For i = 1 To x
fact = fact * i
Next i
MsgBox fact
End Sub 

PS永远不要在VBA中使用Integer,而是选择本机32位整数Long

在代码中,fact的值在任何迭代中都会重新计算,并且不会保留。因此,在最后,只显示最后一个值,即x*i,其中i=x,例如输入的平方。类似这样的东西,使用90%的代码工作:

Sub Factorial()
Dim x As Long, i As Long, fact As Long
x = 5
fact = 1
For i = 1 To x
fact = fact * i
Next i

Debug.Print fact

End Sub

最新更新