CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Aug 2007
    Posts
    12

    simple factoring doesn't work

    hey what's wrong with this i can't find it

    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        int a,b,c;
        cout << "Enter a number ";
        cin >> a;
        for (int n=1; n<a; n++)
        {
            b=a*(a-n);
            c=c+b;
        }
        cout << c;
        return 0;
    }
    its supposed to factor but doesn't!

  2. #2
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: simple factoring doesn't work

    What happens when you step through the debugger?

    Write down the values of a,b,c, and n during each post. You will soon see the problem. If you don't then post the list of numbers and we can go through it....
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  3. #3
    Join Date
    Aug 2007
    Posts
    12

    Re: simple factoring doesn't work

    Yeah, I am really lost here...

    when I entered in 9, it gave the number 2293722, 1 gives 2293672...

    Code:
    b=a*(a-n);
    c=c+b;
    if I entered in 5, it should have made it do this


    5*(5-1)
    5*(5-2)
    5*(5-3)
    5*(5-4)

  4. #4
    Join Date
    Jun 2008
    Posts
    10

    Re: simple factoring doesn't work

    You need to clear c first. Add a statement
    c = 0;
    after
    cin >> a;

    Alan.

  5. #5
    Join Date
    Aug 2007
    Posts
    12

    Re: simple factoring doesn't work

    Quote Originally Posted by Alan-LB
    You need to clear c first. Add a statement
    c = 0;
    after
    cin >> a;

    Alan.
    I did that, and it didn't work (when I entered in 9 it gave 324 instead of 362880)

    It did make the behavior a little better though

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: simple factoring doesn't work

    Oh, you're trying to calculate a factorial? That's rather different than factoring. I was wondering how the heck that code was supposed to work.....

    Assuming overflow isn't a concern, calculating a factorial is a lot easier than you seem to be making it out to be.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured