Hello everyone! I've made an intermediate function for a factorial in which i got some problems with the output.
1 2 3 4 5 6 7 8 9 10 11
longint factorial()
{longint a, b;
cout<<"Ok then! You have chosen wisely..FACTORIAL!"<<endl;
label6:
cout<<"Now please enter your number:";
cin>>a;
cout<<endl;
b=factorial_with_recursion(a);
if(a<0){cout<<"There is no factorial of negative values, my lord!"<<endl; goto label6;}
else {cout<<"Hm.. Let me think! Your result should be.."<<b<<"!"<<endl;};
return 0;}
The "factorial_with_recursion" function is well defined before that so that if i input a as a positive value the program works fine. But if i enter a negative value it is just closing. If any of you can help me i would be grateful. Thank you in advance!
Most people do their factorial something like this
1 2 3 4
unsignedlonglong factorial( unsignedshort n )
{
return( n > 0 ? n* factorial( --n ) : 1 ); //n - 1 might be better I think putting post/pre increment/decrement in functions like that is bad practice
}
*edit also you should not use goto...All you have to do is put factorial() or a do/while
Also your code is ill formatted how can you even read it?
1) line 2 after the curly brace should be on line 3 then shift everything down by one line.
2) the curly brace on line 12 should be on line 13.
3) lines 3-12 should have 4 spaces(tab) and not 1 space in front.
4) on line 9 put each statement on a separate line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
longint factorial()
{
longint a, b;
cout<<"Ok then! You have chosen wisely..FACTORIAL!"<<endl;
cout<<"Now please enter your number:";
cin>>a;
cout<<endl;
b=factorial_with_recursion(a);
if(a<0)
{
cout<<"There is no factorial of negative values, my lord!"<<endl;
}
else {
cout<<"Hm.. Let me think! Your result should be.."<<b<<"!"<<endl;
}
return 0;
}
Also how are you going to do line 8 in your code. There is no parameter for your function and you are passing one.I see thats not your recursion function...Why do you have two? Just make it simple and put them all into one function lol and you should be checking if they are > 0 in your recursion imo.
The indentation is still a problem for me.
Tthe reason why i am not checking if they are > 0 in the function_with_recursion is because writing "There is no factorial of negative values, my lord!" in that function will cause displaying it several times like in a loop (because of the recursivity). And finally i made two functions for this to be able to use the recursivity. Thank you for the indentation advice!
*edit: as for goto i just found out it is not good to use it.. i will try not repeating this mistake in the future.