/***************************************************************************************/
/** Example of a factorial function. */
/***************************************************************************************/
#include <iostream>
using namespace std;
int inputPosInt(string); //Input a positive integer with minimum verification.
unsigned long long factorial(int); //Function for calculating the factorial.
int main()
{
int d = inputPosInt("Please enter a positive integer: ");
unsigned long long l = factorial(d);
if(l == 0) //The function returns zero if the result is larger than ULLONG_MAX.
{
cout << "Too many to calculate factorial." << endl;
}
else
{
cout << "The factorial of " << d << " is " << l << endl;
}
return 0;
}
/******************************************/
/**Function for calculating the factorial.*/
/******************************************/
unsigned long long factorial(int d)
{
unsigned long long l = 1;
if(d == 0) return 1;
do
{
l*=d--;
if((d>0)&&((ULLONG_MAX/d)<l)) return 0; //Return zero if the result is larger than ULLONG_MAX
}while(d>0);
return l;
}
/** Function for entering a value of type "int" with validation. */
/** The string in the argument is needed to prompt for data entry. */
int inputPosInt(string s)
{
int d;
bool b;
do{
b = true;
cout << s;
cin >> d;
if(!cin) //If incorrect characters are entered, then clear the input buffer and ask to enter again.
{
cout << "The input is not correct. Try again.\n";
cin.clear();
while (cin.get() != '\n');
}
else
{
if(d >= 0)
{
b = false;
}
else
{
cout << "The input is not correct. Try again.\n" << endl;
cin.clear();
while (cin.get() != '\n');
}
}
}while(b);
return d;
}
Comments
Leave a comment