Hey!
I'm currently writing a program that calculates the factorial of a given number. This number has to be positive, and it has to be an integer, ie, not a decimal.
I got the integer part working, using limits, which is shown in the code below. I also then needed to add a bit where if the user enters a negative number that an error message appears and the user is prompted to re-enter a number.
I must stress that I have literally been using C++ for one week, so I am extremely new to this!
When I enter in a decimal number, it displays the error message and asks the user to re-enter. However, when I enter in a negative number, it gives the factorial to be 1, rather than displaying the error message.
In trying to fix this problem I now receive the error message when compiling:
"Stirling.cc: In function `int main()':
Stirling.cc:14: error: expected primary-expression before "else"
Stirling.cc:14: error: expected `;' before "else"
"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <cmath>
#include <limits>
#include <iostream>
using namespace std;
int main(){
int n;
while (true) {
cout << "Enter a positive integer" << endl;
cin >> n;
if (cin.peek() == '\n' && cin.good()) break;
cout << "Invalid input! Try again...\n" << endl;
do { cin.ignore(numeric_limits<streamsize>::max(), '\n'); } while (!cin);
else if (n<0)
cout << "Invalid imput! Try again!" << endl;
cin.clear();
do { cin.ignore(numeric_limits<streamsize>::max(), '\n'); } while (!cin);
}
if (n <= 50)
{
double result=1;
for (double i=1; i<=n; ++i){
result=result*=i;
}
cout << "The factorial of this is " << result << endl;
}
else if (n > 50);
{
const double PI = 3.141592;
double factorial1 =(n*log(n));
double factorial2 =(n);
double factorial3 =(0.5*log(2*PI*n));
double x = factorial1-factorial2+factorial3;
double xfac = exp(x);
cout << "The factorial of this number is " << xfac << endl;
}
}
|
Any help would be greatly appreciated!