阶乘函数返回平方数而不是阶乘

Factorial function returning squared number and not factorial

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

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 

在您的代码中,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

练习循环和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.