how to add a factorial ()

This is a discussion on how to add a factorial () within the C++ Programming forums, part of the General Programming Boards category; Greetings, This may sound like a silly question but I want to add this factorial function inside my calculator w/o ...

  1. #1
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378

    how to add a factorial ()

    Greetings,
    This may sound like a silly question but I want to add this factorial function inside my calculator w/o really changing my calculator that I worked hard on to create. How can I add this into my calculator w/o changing everything? Any ideas?
    Code:
    #include <iostream>	//cin, cout, <<, >>
    #include <conio.h>
    #include <cctype>	// for strings
    #include <cassert>	// for assert()
    using namespace std;
    
    #define nl "\n"
    int Factorial(int n);
    
    
    float first, second, answer;
    char o, y;
    int n;
    
    int main()
    {
    
    	do	{
    			cout<<"Type a sum (format: a number +,-,*,/ with another number): ";
            	cin>>first>>o>>second;	//inputs number, operator, number
            	switch (o)	// upon your selection, it selects the operator you chose
    
    				{
                		case '+': answer = first + second; break;
                		case '-': answer = first - second; break;
                		case '*': answer = first * second; break;
                		case '/': answer = first / second; break;
                		default:
               			cout<<nl<<"Error: format: +,-,*,/ number"<<nl	//Error: defaults message
    						<<"Press any key to continue...";
                		getch();	//get a character
               			return 1;
               		}
                cout<<nl<<"The Answer to "<<first<<o<<second<<" is: "<<answer;	//output answer
                cout<<nl<<"Do you want to do another sum? ";	
                y = toupper(getche());	// change y to Y
                cout<<nl;
            }	while (y == 'Y');	//if equals y then do loop again
    	return 0;
    }
    
    int Factorial(int n)   //want to add it
    {
    	assert(n >= 0);
    	double product = 1;
    
    	while (n > 1)
    		{
    			product *= n;
    			n--;
    		}
    	return product;
    }

  2. #2
    Registered User
    Join Date
    Aug 2002
    Posts
    170
    Simply make your function recursive. Meaning call it from within itself.

    double factorial( double num )
    {
    if( Num == 1)
    return(1);

    return(num*factorial(--num));
    }

    I haven't tested this, I just wanted to give an idea of how you might code it.
    Best Regards,

    Bonkey

  3. #3
    Registered User
    Join Date
    Aug 2002
    Posts
    170
    I think i misunderstood your question. If you just want to know how to add your existing function into your code?

    I would add a

    case '!': answer = factorial(first);
    Best Regards,

    Bonkey

  4. #4
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Your code in main assumes the expression is of the form

    literal operator literal

    while for a factorial the sequence would obviously only be

    literal operator (IE 5!).

    You have two options, one easier for you, the other easier for the users.

    This is the easy way, have an option to select which format, IE, one for binary functions (+-*/), one for unary functions (factorial, sin, exp, etc before they enter the expression. From the user perspective, they have to give reduntant information, which isn't fun. From your perspective, it makes the code a lot easier.

    The harder way is to be more general in your form of input and then extract (parse) the neccesary information. Input a string expression, determine if it's a binary or unary expression, and then evaulate it. Parsing itself can become really complex.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  5. #5
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378
    THANKS!
    Both silentstrike and bonkey for your input it worked.

  6. #6
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    Or you can make another menu on top of the one you have. Such as entering a 1 for normal operations and 2 for the factorial. You may expand it later if you want to add features.

    However, I do like SS's idea of string parsing: split up the line into tokens and look for operators and operands. This way you can do stuff like !3 * 2 + 4...
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  7. #7
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378
    However, I do like SS's idea of string parsing: split up the line into tokens and look for operators and operands. This way you can do stuff like !3 * 2 + 4...
    Cool!
    I like that idea too! Thanks! Cshot!

  8. #8
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Originally posted by bonkey

    double factorial( double num )
    {
    if( Num == 1)
    return(1);

    return(num*factorial(--num));
    }
    This code won't work.
    Replace "--num" with "num-1" and it will work.
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  9. #9
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    double factorial( double num )
    {
    if( Num == 1)
    return(1);

    return(num*factorial(--num));
    }

    This code won't work.
    Replace "--num" with "num-1" and it will work.
    You also need to change if(num == 1) to if(num == 0) and make sure num isn't a negative value to begin with.
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  10. #10
    Registered User
    Join Date
    Aug 2002
    Posts
    170
    Originally posted by Cshot
    You also need to change if(num == 1) to if(num == 0)
    Why? I mean it's ok to to that, but its not needed. X*1 = X there is no need to iterate to 0 before stopping.
    Best Regards,

    Bonkey

  11. #11
    Green Member Cshot's Avatar
    Join Date
    Jun 2002
    Posts
    892
    0! = 1

    If you pass in 0, the program will fail.

    Why?
    Because in that code you'll get 0 * -1 * -2 * -3 * ....
    Try not.
    Do or do not.
    There is no try.

    - Master Yoda

  12. #12
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    While we're at it...
    There are even more problems with bonkeys function.

    With large doubles (d-1) == d because of lack of precision.
    What happens when a large double is passed to the function? It crashes!
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  13. #13
    Registered User
    Join Date
    Aug 2002
    Posts
    170
    Originally posted by bonkey
    Simply make your function recursive. Meaning call it from within itself.

    double factorial( double num )
    {
    if( Num == 1)
    return(1);

    return(num*factorial(--num));
    }

    I haven't tested this, I just wanted to give an idea of how you might code it.

    Glad I am wearing my flame retardant underoos.
    Best Regards,

    Bonkey

  14. #14
    TransparentMember correlcj's Avatar
    Join Date
    Jun 2002
    Posts
    378

    Good thing is right, bonkey.

    They're really on it tonight!
    The dragons spittin flames...
    BTW dragon
    Whatever is said in Latin sounds definitely profound.
    Later gator!

  15. #15
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    Recursive descent is pretty easy to learn and you
    can make a pretty good calculator.
    I attached an example of this technique. It's not good programming style
    but allows you to do basic stuft like
    4 + 4;
    8.000000
    4 * (3 + 5) + 3!;
    38.000000
    pow(0, 0) * 3;
    3.000000
    pow(2, 5) * pow(2, 6);
    2048.000000
    3 /4;
    0.750000
    4 / 5;
    0.800000
    4 + 3 /3;
    5.000000
    0/0
    ;
    Attached Files Attached Files

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Factorial
    By foxman in forum Contests Board
    Replies: 27
    Last Post: 07-11-2008, 06:59 PM
  2. FACTORIAL. Can you hel me about this
    By Melody in forum C Programming
    Replies: 57
    Last Post: 11-20-2007, 07:32 AM
  3. Recursion
    By Lionmane in forum C Programming
    Replies: 11
    Last Post: 06-04-2005, 12:00 AM
  4. Basic Factorial from 1-10
    By AaA in forum C Programming
    Replies: 20
    Last Post: 05-28-2005, 07:39 AM
  5. Add a dialog box to a tab
    By axr0284 in forum Windows Programming
    Replies: 0
    Last Post: 01-10-2005, 07:38 AM

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