I'm very new to C++ and I'm making a program that calculates the factorial of a number. Just in case someone doesn't know, the factorial of a number is the sum of all numbers starting at 1 and ending at the number itself. Eg. The Factorial of 3 = 1 + 2 + 3 = 6.
So here is my code uptill now:
#include <iostream>
usingnamespace std;
void Welcome(double& num)
{
cout << "Hello! This program will help you calculate the factorial of any number" << endl << "Enter any positive number: ";
cin >> num;
return;
}
void Check(double& num)
{
for (int i = 0; i < 1;)
{
int a = int(num);
if (num - a != 0 || num < 0)
{
if (num - a != 0)
{
cout << "Error. Enter an integer: ";
cin >> num;
a = int(num);
}
if (num < 0)
{
cout << "Error. Enter a positive number: ";
cin >> num;
}
if (num >= 0 && num - a == 0) break;
}
}
return;
}
main()
{
double num;
Welcome(num);
Check(num);
cout << num << endl; // Only checking if the above functions are working
system("Pause");
return 0;
}
When I compile that, the Welcome function works fine. But when I enter 5 (For example), a valid input, the cursor goes to the next line and keeps blinking:
Hello! This program will help you calculate the factorial of any number
Enter any positive number: 5
If I enter -5, it will ask me to enter a positive number. Then if I enter 4, for example, it hangs again:
Hello! This program will help you calculate the factorial of any number
Enter any positive number: -5
Error. Enter a positive number: 4
But lets say I enter 4.5. It will ask me to enter an integer, so I enter 5. Then the program works fine and outputs 5:
Hello! This program will help you calculate the factorial of any number
Enter any positive number: 4.5
Error. Enter an integer: 5
5
Press any key to continue . . .
I already made a simple program like that once but now I wanted to make it more complex. I want to the user to be able to enter any number he wants and the program should decide whether or not the input is valid. As I said before, the above code is not complete. The calculations aren't done yet. And maybe unknowingly, you answered my question! I had an extra 'if' for some reason.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
if (num - a != 0 || num < 0) // This one was unnecessary
{
if (num - a != 0)
{
cout << "Error. Enter an integer: ";
cin >> num;
a = int(num);
}
if (num < 0)
{
cout << "Error. Enter a positive number: ";
cin >> num;
}
if (num >= 0 && num - a == 0) break;
}
HAHA. God knows why I did that. I resumed this program after a long time, maybe that's why. But Thank you!