Using a variable as a power

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TamaThps
    New Member
    • Oct 2008
    • 12

    Using a variable as a power

    How can I use a variable as a power in C++

    for example an equation n^n
    should pow(n ,n) work?

    I have a program for a class where a variable FIRST is the first number inputted from a file. I need to then work out the factorial using the equation
    n! = e^(-n)*(n^n)*sqrt(2 *pi*n)

    Using FIRST as my variable instead of N I came up with the following equation:
    FACTORIAL = (((pow(2.718281 83, (-FIRST))) * (pow(FIRST, FIRST)) * sqrt(2 * 3.14159265 * FIRST)));

    I am getting some overloading errors which I believe are due to the fact that I used a variable as the power instead of an integer?

    How would one go about writing this equation using FIRST as my variable for N (FIRST happens to equal 6 if that makes any difference)?

    This is my first C++ class so I am new to this. Any help would be great! thanks.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    Originally posted by TamaThps
    I am getting some overloading errors...
    Works fine for me, and probably for others too. So you have to post verbatim text of these errors.

    Comment

    • archonmagnus
      New Member
      • Jun 2007
      • 113

      #3
      Just a quick thought...

      You may be getting overloading of the "pow" function. Look up the function declarations of pow() relative to the variable type of "FIRST" (in your case). In other words, you may have to cast "FIRST" to either a float or a double to match one of the overloads.

      For example:
      [code=cpp]
      FACTORIAL = (pow(2.71828183 , (double)(-FIRST))
      * pow((double)FIR ST, (double)FIRST)
      * sqrt(2.0 * 3.14159265 * (double)FIRST)) ;
      [/code]

      As an aside, the obsessive-compulsive side of me wanted to fix your "mixed-mode" operations as well (integers multiplied with doubles, etc.). It's really not that big of a deal, but like I said, I have mild OCD.

      Comment

      • TamaThps
        New Member
        • Oct 2008
        • 12

        #4
        Thank you. It was overloading the pow() function. It is now working correctly. So when using a variable as the exponent or power you should define it as a double?
        FIRST is defined as a float at the beginning of the code.

        Comment

        • boxfish
          Recognized Expert Contributor
          • Mar 2008
          • 469

          #5
          pow can take either two doubles or two floats. Reference page on pow.

          Comment

          Working...