Grr!

Oct. 18th, 2006 04:44 pm
hazliya: (Default)
[personal profile] hazliya
I need help with my C++ program!

Someone? It's due tomorrow morning. I just neeeed help soon. Mostly? How do I put 5! (5x4x3x2x1) into C++? And why won't my while loop work? =(

Help?

-Haz

Date: 2006-10-18 09:20 pm (UTC)
From: [identity profile] qedrakmar.livejournal.com
I found this on a google search
// factorial calculator
#include 
using namespace std;

long factorial (long a)
{
  if (a > 1)
   return (a * factorial (a-1));
  else
   return (1);
}

int main ()
{
  long number;
  cout << "Please type a number: ";
  cin >> number;
  cout << number << "! = " << factorial (number);
  return 0;
}

Date: 2006-10-18 10:30 pm (UTC)
From: [identity profile] lopaanre.livejournal.com
That would be how to do factorial recursively. To do it by simply using a for loop you would do:

int factorial(int a)
{
int f = 1;
for(int i=1;i<=a;i++)
{
f = f * i;
}
return f;
}

so what that does is go through a for loop (starting at 1 and ending when i > a) and multiplies f by i. Then it returns the calculated value. I assume you wanted this for a larger program as such I made it as a function. If you want the entire program to only do factorials, then use the main function that the person above me posted.

Also, I can't remember C++ that well, does int go higher than 255? If it doesn't you probably want to change int to long.

If that didn't really answer your question call me, if you still have my number. If not send me an email.

Date: 2006-10-19 05:28 am (UTC)
From: [identity profile] chainer36.livejournal.com
If it's a 32-bit int, then the max signed value is 2147483647.
For a 16-bit int, it's 32767.

I think you should have much of a problem.

Another way of doing JonAdler's program is

int factorial (int a)
{
for (int i = (a-1); i>1; i--)
{
a = a*i;
}
return 1;
}

But his way is simpler. Mine just forces you to count down to one, rather than up to a.

But mine is obviously bettar, since a > f.

Date: 2006-10-19 05:29 am (UTC)
From: [identity profile] chainer36.livejournal.com
shouldn't *

Meant to add that. -.-

December 2011

S M T W T F S
     123
45678910
111213141516 17
18192021222324
25262728 293031

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Mar. 16th, 2026 04:53 am
Powered by Dreamwidth Studios