0
What is wrong in this code
#include <iostream> using namespace std; int fact(int n) { if ( n >= 0) { if ( n==1 || n==0 ) { return 1; } else { return n*fact(n-1); } } else { cout << "Sorry Wrong No "<< endl ; } } int main() { int a; cout << "Enter The No ="<< endl ; cin >> a; cout << "Factorial ="<< fact(a) ; return 0; }
5 Answers
+ 3
When you give a negative number as input it gives some sort of additional number like 4620160.This code will solve that problem.
you can use this code :
#include <iostream>
using namespace std;
int fact(int n)
{
if ( n >= 0)
{
if ( n==1 || n==0 )
{
return 1;
}
else
{
return n*fact(n-1);
}
}
else
{
// cout << "Sorry Wrong No "<< endl ;
return 0;
}
}
int main()
{
int a,b;
cout << "Enter The No ="<< endl ;
cin >> a;
b=fact(a);
if(b!=0)
cout << "Factorial ="<< b ;
else
cout<<"sorry wrong no";
return 0;
}
+ 1
I just ran it and it worked fine. What compiler are you using?
0
what is the error you get while compiling ?
0
This code is giving a factorial for negative no alsođ€
0
M using this app