So I am making a factor recurring program for Uni and I haven't used for loops very often,
The idea is that you input a positive number and it does the calculation for you, e.g. if the number 5 was chosen it would do the following:
1*2*3*4*5 = 120, it is working for most of my inputs but it doesn't get it right when I go pass 1
Just wondering if anyone knows what is wrong with my foor loop.
#include <iostream>
using namespace std;
int main() {
int i, n, factorial = 1;
cout<<"Enter a positive integer: ";
cin>>n;
if (n<=0) {
cout << "Please enter a non-negative number!!!\n";
}
else {
for (i = 1; i <=n; ++i) {
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
}
I am also planning so that when the number gets too big it goes into scientific notation, but I need to get this working first.
When I input 9 it does the calculation correctly:
1*2*3*4*5*6*7*8*9 = 362880
The way I have got it to be printed is:
Enter a non-negative integer:
9! = 362880
When I enter a number greater than 12, e.g. 13 I get
Enter a non-negative integer:
13! = 1932053504
The answer is wrong and also I need it to be:
Enter a non-negative integer:
13! = 6.22702e+09
Cheers.