--Originally published at OlafGC / Class #TC1017
Long time no see you, guys. This is a blog post for the WSQ06, which is a factorial calculator. The tricky part is to write down the function, to understand the logic of the factorial numbers to teach it to the computer. I used a float because when you get the factorial of a big number things get pretty nasty for an int. And in the end, you just need to write a loop in case the user wants to run the program again (which we’ve already done dozens of times).
Code:
#include <iostream>
using namespace std;
float factorial(float n)
{
float result;
if(n>0)
result=n*factorial(n-1);
else if(n==0)
result=1;
return result;
}
main ()
{
float num, res;
char op;
do{
cout<<“Write the number you want to convert:”<<endl;
cin>>num;
res = factorial(num);
if(res==0)
cout<<“You cannot get factorials from negative numbers.”<<endl;
else{
cout<<“The factorial number is: “<<res<<“.”<<endl;
}
cout<<“Do you want to calculate another number? (y/n) “;
cin>>op;
if(op==’N’||op==’n’)
cout<<“Have a nice day!”<<endl;
else
cout<<“Let’s go again!”<<endl;
}
while(op==’Y’||op==’y’);
return 0;
}