combination(math) function and if statement help

This is a discussion on combination(math) function and if statement help within the C++ Programming forums, part of the General Programming Boards category; Basically i wrote a factorial function that works like a charm and planned on using it in this combination function ...

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    10

    combination(math) function and if statement help

    Basically i wrote a factorial function that works like a charm and planned on using it in this combination function that I wrote. But some of the combinations (nCr) that I need to use have a 0 value for r. This means that somewhere in the calculation I am dividing by zero which gives me an error. I tried to put in an if statement so that if r == 0 to output 1 instead but it is just outputtong random ints instead of 1. Here it is:
    Code:
    int nCr (int n, int r)
    {
         if (r!=0) //if r is not 0 do the calculation and store it.
        {
         long double nCr = factl(n)/(factl(r)*factl(n-r));
        }
    
        else //otherwise store the value 1 instead.
        {
         int nCr = 1;
        }
    
    }
    instead of getting 1 i am getting 4288548 in my output. Any help would be greatly appreciated.

  2. #2
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    change int nCr = 1;
    to nCr = 1;

    When you use "int" again you are creating a new local variable. (Local to the section in brackets>)

  3. #3
    Registered User
    Join Date
    Feb 2003
    Posts
    10
    i removed it and got 2 compile errors.

    factl.h:28: assignment of function `nCr(int, int)'
    factl.h:28: assignment to `int ()(int, int)' from `int'

    line 28 is the line that i removed int from.

  4. #4
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398
    Shoot! That's what I get for trying to answer a question when I'm not at my compiler (and maybe not reading carefully). Sorry.

    It looks like you're trying to use nCR as both a function and as a variable.

    Do you want that function nCR to return 1 under the divide by zero condition?

    Just change that line to return 1;

    You also need to return a value if you're not dividing by zero
    maybe return factl(n)/(factl(r)*factl(n-r));

  5. #5
    Registered User
    Join Date
    Feb 2003
    Posts
    10
    yup that did it, thanks!
    im new to making my own functions, we havent learned it in my intro. to programming class yet and i was just fooling around with it.
    Thanks again

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21