#include <iostream.h>
int factorial(int);
void main(void) {
int number;
cout<<"\n\n"<<" Please enter a positive integer: ";
cin>> number;
cout<<"\n\n";
if (number > 0)
cout<<" The "<<number<<"! is "<<factorial(number)<<"\n\n\n\n";
}
int factorial(int number) {
int temp;
if(number <= 1) return 1;
temp = number * factorial(number - 1);
return temp;
}
ah ok I figured it out, had to use a calculator to realize what I was doing wrong:
change negFactorial to this:
1 2 3 4 5 6 7 8
int negFactorial(int number)
{
if (number >= -1)
return -1;
elsereturn (number * negFactorial(number+1));
}
the output of this will be a positive number, however on the calculator this is the same if you press the multiply sign twice, switching between negative and positive 24, so all you need to do is add a negative sign in output: " is -"
1 2 3
elseif (number<0)
cout << " The " << number << "! is -" << negFactorial(number) << endl;
else
Basically, as much as possible your main must be of type int (default? correct me if I'm wrong) It must return something. (to end the program? return 0).
np, also note that the program does not validate input, so if the user enters jumbled text "hello my name is bob", or fractions "6.34332" this will probably not work as intented, a better way to rewrite this would be to validate using a loop, maybe getting even up to a fractional and then casting to an int. compiler will give warnings but these can be ignored as this is what we want.
as far as main goes, void main() is just poor programming, as the program makes no attempt to be automated. for instance, say I write a much larger program, and part of my big huge program takes your little factorial program and uses it, if an error was to occur your program will not let me know (no return 1...119) in fact if it runs smoothly and everything works it doesn't let me know this either. (no return 0) Return 0 is an exit status, 0 means the program exited correctly, it went though all the code and then passed 0 back to the program or operating system.
Take the C++ compiler you use, when you compile code that compiler is a running program... If you have errors in your code it returns the errors and usually an exit status 1 on the last line (error). However when there is no errors, the code simply compiles. The compiler does send back an exit status of 0 but we never see this, as the operating system you use considers exit status 0 to be successful. The operating system will only tell you if you get an exit status of 1 or higher(error), not exit status 0 (no error).