Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

My factorial program keeps returning wrong values

$
0
0
here is my code:
#include <iostream>
using namespace std;

long fact(int x);

int main()
{
	int num1;

	cout << "Hello, please enter a whole number(1, 2, 3...) to find its factorial." << endl;
	cout << "Please do not use decimals." << endl;

	cout << ":: ";
	cin >> num1;

	cout << "The number " << num1 << "'s facorial is: ";
	cout << fact(num1) << endl;
}

long fact(int x)
{

	for(int num = x; num > 1; num--)
	{
		x = x * (num -1);
	}

return x;
}



So here is the issue. If any number below twelve is used, then the program works as expected. Any value above 12 gives me either a large number that is not a correct factorial or it gives me a number that is not correct and has a - sign at the front. I think it much have something to do with the variable type(as you can see I tried to have the function return a 'long' value but I don't think I did that right), but maybe my code is wrong in other places?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>