Thread: simple calculation question.

  1. #1
    Registered User
    Join Date
    Dec 2013
    Posts
    241

    simple calculation question.

    I wrote a function to do factorization (n!).

    while this function works perfectly:
    Code:
    int fact (double x){
    register int z=1; 
    if (x==0)
        return 1;
    else 
        for(x;x;x--)
            z*=x;    
    return z;        
    }
    this doesn't:
    Code:
    int fact (double x){
    if (x==0)
        return 1;
    else 
        for(x;x;x--)
            x*=x;    
    return x;        
    }
    what makes the second one different from the first one? can't see the difference..

  2. #2
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by Dave11 View Post
    what makes the second one different from the first one? can't see the difference..
    In the first you are accumulating an answer into a variable z. In the second you don't have the accumulator variable anymore, so x gets continuously overwritten, leading to probably undesirable results.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple calculation going to 0 every time
    By summit45 in forum C++ Programming
    Replies: 4
    Last Post: 08-08-2013, 02:21 PM
  2. noob help with very simple calculation
    By blastfromthepas in forum C Programming
    Replies: 1
    Last Post: 10-31-2009, 04:05 AM
  3. simple calculation of division
    By steve1_rm in forum C Programming
    Replies: 2
    Last Post: 09-13-2008, 05:37 AM
  4. Simple calculation not working, need help
    By Summonerur in forum C Programming
    Replies: 20
    Last Post: 09-24-2004, 02:53 PM
  5. Repeating a simple calculation
    By FloatingPoint in forum C++ Programming
    Replies: 2
    Last Post: 07-21-2003, 07:33 AM