1 2
|
cout<<"Calculating: 0"<<endl;
cout<<factorial(1)<<endl;
|
That is cheating. Modify your factorial function to accept 0 as an input. (you may want to handle negative numbers, too)
tmp = n * (factorial(n - 1));
The problem here is that the if the overflow occurs you don't see it.
i really dont even understand why its wrapping arround rather then going negative. |
Suppose a 1 byte number. The maximum positive is 127, minimum negative -128, total numbers 256.
Now you do
100*4 this give you
400, overflows, so is taken module 256.
400%256 = 144, which is a positive number! and bigger than the one you have before.
So all comes to the false assumption that when overflows, the number turns out negative (or less that its previous value).
Just to clarify, that was just an example of how the information was presented. I don't know what the system does in case of overflow (the module 256 could be wrong).
1 2 3 4
|
int tmp = factorial(n-1); //this is "safe" (if it wasn't, an exception was throw before)
if( std::numeric_limits<int>::max()/n < tmp ) //checking if the operation will fail
throw n;
return n*tmp; //performing the operation
|
About exceptions.
An error occurs, you don't know how to handle it.
Then you derive it to your supervisor that will know what to do (or will derive it to other)
If you can handle the error right where occurs, then you don't need exceptions.
Consider your factorial function.
You detect an overflow, put an error message, but then you give an incorrect value to the caller.
And the caller doesn't know that the value is incorrect.