Let’s make a factorial calculator!
First of all, we have to know what a factorial number is. If you see a number that is accompanied by an exclamation sign, you’re seing a factorial number, that consists in a number multiplied by all the precedent integer numbers until reach one. For example, 6!= 65432*1 = 720.
Knowing that, we can proceed to elaborate the code. We are going to create a function, of type “long double”, which is in charge of calculating factorial numbers.
You can see what I did in the following code.
// Using long double to obtain big values of factorial numbers #include <iostream> #include <math.h> using namespace std; long double fact (long double n) { long double R=n; if (n==0) {R=1;} for (n--; n>0; n--){ {R*=n;} } return R; } int main() { long double N; long double n; char C='Y'; do { if (C!='Y' && C!= 'y') {cout << "\n\nInvalid choise! \nTry again"<< endl;} else { cout << "\nNon-negative integer: "; cin >> N; n = floor(N); if (N<0) {cout << "\nMATH ERROR! \nPlease, introduce a NON-NEGATIVE number\n\n" << endl;} else if (N!=0 && (N/n)!=1) {cout << "\nMATH ERROR!\nPlease introduce an INTEGER number!\n\n";} else {cout << "\n" << N << "! = " << fact(N) << "\n\n";} } cout << "\nDo you want to introduce another number?\n(Yes = Y / No = N)\n\n"; cin >> C; } while (C!='N' && C!='n'); cout << "\n\nHave a nice day!!\n\n\n"; return 0; }