First, I'd just like to say, "FINALLY!" After searching around for 20 minutes, I found out how to register and login, and another 20 minutes were spent finding the "New Topic" button. Anyways, onward!
So I tried to get a program to calculate factorials. I know I can add in some user input for what number that they want to "factorialize", but that's not the problem. As of now, the main problem is that it's inaccurate. Here's my code:
Note that when I set the precision to less than 132, it displays e+132. When I set the precision to greater than 132, it gets rid of the "e". Now, this is not a request for you to do my homework. If I wanted to cheat on homework, I could have just copied this code found here: http://www.daniweb.com/code/snippet216490.html . No no, I truly want to know what went wrong with my own code. Oh yeah, how do I know it's wrong? Because I checked it with the output from the code of the link I gave. Plus, I just know.
(x>=1)e+132 == (x>=1)*10^132, which has at least 133 digits. Calling std::cout.precision(x) means "print in scientific notation floating point values with more than 132 digits".
There's no type large enough to accurately represent 100!.
Also, 100! ~= 9.3326e+157, but your initialization of hundredfactorial greatly skews the result. For calculating factorials (or any other operation that requires iterated multiplication), the accumulator should be set to 1.
Helios is right, 100! is too big. Try it with a smaller number. It's easier to verify too. For example, we could easily verify with pen and paper that 5! = 120. Also, recursion comes very naturally for factorials.
Although in that case, he is using tail recursion so the compiler *might* be able to optimize it for you. Although a for loop is still better IMO then using a recursive function...
Good point. Recursion is indeed terribly inefficient. But for calculating the factorial of n < 25, and assuming you run this on a modern computer system, it's much more elegant and readable.
Of course, if you're actually writing a commercial software, you should avoid recursion.