C++, calculate factorial | Sololearn: Learn to code for FREE!

+1

C++, calculate factorial

How can I avoid the negative case. Below my codes not working properly in the n=-1. #include <iostream> using namespace std; int factorial(int n) { if (n==1 || n==0) { return 1; } else if (n > 1){ return n * factorial(n-1); } else { cout << "negative number" << endl; } } int main() { cout << factorial(-1); }

c++

5/28/2018 10:20:11 PM

Dr. İsmail ÖZBAKIR

6 Answers

New Answer

+2

Here is how I would do it İsmail ÖZBAKIR : else { return -1; } int main() { int answer = factorial(-1); if (answer <= -1) { cout << "Negative number invalid"; } else { cout << answer << endl; }

+1

You can't do that using recursion, because in C++ you can't return multiple types. You would have to throw an exception error and catch it when you call it in main.

0

You still need to return an integer. You can't use cout with a function using cout; that's like doing this: cout << cout << ...

0

how could i return string in this case ?

0

great :) thank you very much Zeke Williams

0

Return -1 if input is under 0.