So it's 5:00 A.M. where I am and I am confused and frustrated as hell. I've created a program like this before but can't understand what is going on.
I've created a very simple factorial program and have double checked the logic, but every time I enter a number greater than 2 the program goes into a loop constantly printing out "inf". I can't see ANYTHING wrong with the program itself. :(
#include <iostream>
using namespace std;
int main() {
double userNumber = 0;
double i = 1;
cout << "This program will calculate the factorial of the number you enter.\nPlease enter your number now: ";
cin >> userNumber;
for ( i = 1; i < userNumber; i++ ) {
userNumber *= i;
cout << userNumber;
}
cout << "\n\nThe factorial is " << userNumber << "." << endl;
return 0;
}
It works for 1 and 2:
But as soon as you do 3 or greater....
I haven't created a C++ program in a while but can't for the life of me see what is wrong. Is this just a super obvious syntax error, or is my computer finally breaking down on me?
EDIT: I just changed the numbers from double to int and this is what I got:
I still don't understand why it is doing this. I don't see a problem with the for loop, or anything else...
Argh. Smashes head into desk
Change
for ( i = 1; i < userNumber; i++ ) {
to
for ( i = userNumber - 1; i > 1; --i ) {
Note that your code changes userNumber
in the loop body, so that the loop will only terminate if userNumber
overflows.