Visual Basic 6

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • col1855
    New Member
    • Mar 2006
    • 1

    Visual Basic 6

    I am teaching myself Visual Basic 6
    Is there a function for the factor of a number, ie 5*4*3*2*1
    and can each answer be written to file
  • Nmixer
    New Member
    • Mar 2006
    • 4

    #2
    (sorry not sure)
    I'm guessing your making a calculator that deals with Factorials ( ! )
    If so maybe VB already can do them, just use the factorial symbol ;)

    [edit] ^ that didn't work i tryed. so try what i posted underneath. good luck.

    Public Function Factorial(n As Byte) As Long
    Static f() As Long 'stores the factorials calc thus far
    Static h As Long 'stores the highest numbered facorial so far

    'if we haven't calc that high yet, then redim and perserve!
    If h < n Then
    ReDim Preserve f(0 To n) As Long
    End If

    'set the first two manually!
    'i would have an "If" here, but it wasn't working, so, yea
    f(0) = 1

    'now, if we hadn't gotten to the high value, loop from the
    ' next value to the one we want, calculating each time
    Dim x As Integer
    For x = h + 1 To n
    f(x) = f(x - 1) * x
    Next

    h = n
    Factorial = f(n)
    End Function
    Last edited by Nmixer; Mar 25 '06, 07:46 PM.

    Comment

    • bradboy199
      New Member
      • Apr 2006
      • 2

      #3
      you can create some code that will act like a function

      Dim Number as Long, Factorial As Long, N as Long
      Factorial=1
      For N = Number to 1
      _____Factorial= Factorial * N
      Next N

      Factorial will be your answer. It can be stored in any way that a variable can be stored.

      _____Indicates an indent, it really doesn't matter, but ya know you have to do it.

      Comment

      • Helmer
        New Member
        • May 2007
        • 10

        #4
        heres another way t do it:
        Dim Input as single
        Dim Output as Single

        Output=Input
        for x= input to 2
        Output=Output*( Input-1)
        next x

        'where input is the number befor the factorial sign(!), and output is well your output
        nice an simple as the factorial is the number multiplied by number- 1, untill number-1= 1 as if it went till number=1 then you would multiply by 0 and poof pointless :P

        Tell me wat u think

        Comment

        • Killer42
          Recognized Expert Expert
          • Oct 2006
          • 8429

          #5
          Since a couple of people have come up with much the same code, I'll put it into a simple Public Function and post it in the Articles section.

          Comment

          Working...