calculating n factorial

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • becky808
    New Member
    • Oct 2008
    • 1

    calculating n factorial

    Hi,

    I'm trying to write a program to calculate n factorial but it won't compile. Can anyone tell me what I'm doing wrong?

    #include <iostream>
    #include <cmath>

    using namespace std;
    int main(){

    int n;
    float factorial;
    float lnFactorial;

    cout << "Please enter a positive integer:" << endl;
    cin >> n;

    {
    if (n%2 == 0){

    }
    else if ((n+1)%2==0){

    }
    else {
    cout << "Please enter a positive integer:" << endl;
    }
    }
    if (n<0){
    cout << "Please enter a positive integer:" << endl;
    cin >> n;
    }
    else if(n==0){
    cout <<"n! == 1" << endl;
    }
    else if(n<=50) {
    {for(int i=n; i>=1; i--){
    factorial *= i;
    }

    cout << "n! == " << factorial << endl;
    }
    else{
    {lnFactorial = (n*log(n)) - n;
    factorial = exp(lnFactorial );
    }
    cout <<"n! == " << factorial << endl;
    }

    return 0;
    }
  • archonmagnus
    New Member
    • Jun 2007
    • 113

    #2
    For one thing, it looks like you have an excess in the number of braces you have. Specifically, in the segment:
    [code=cpp]
    else if(n<=50)
    {
    {for(int i=n; i>=1; i--)
    {
    factorial *= i;
    }

    cout << "n! == " << factorial << endl;
    }
    else
    {
    {lnFactorial = (n*log(n)) - n;
    factorial = exp(lnFactorial );
    }
    cout <<"n! == " << factorial << endl;
    }
    [/code]

    You have extra braces preceeding "for(int i=n; i>=1; i--)" and "InFactoria l = (n*log(n)) - n;". Please don't think I'm criticizing your code, but if I may suggest using a better visualization/spacing technique, it would help you to be able to see these fixes a bit easier.

    Comment

    • whodgson
      Contributor
      • Jan 2007
      • 542

      #3
      I suggest you write a simple factorial fuction and then a basic test driver. You can write a fancy main later. Also it would help if you enclosed your
      Code:
      code
      say:
      Code:
      double fact (int n)
      {
          if (n<0) return 0;
            double f=1;
             while(n>1)
                f*=n--;
                return f;
      }
      you can substitute your function for the above later after it compiles and runs properly The test driver only needs a for loop from within which you call fact()

      Comment

      Working...