Factorial code, stuck for some reason, help!

2 views (last 30 days)
Praketa
Praketa on 27 Mar 2014
Edited: James Tursa on 27 Mar 2014
function fact2=fact(n)
%function to write factorials
if n<1
disp('incorrect answer')
disp(' ')
n=input('Enter new value of n:')
else
ans=1;
while n>1
ans=ans*n;
n=n-1;
end
end
fact2=ans;
This is my code intended to calculate factorials. I am trying to put a check if accidentally some body inputs a negative number then it should give user to correct the error. but this not working for some reason!

Answers (1)

James Tursa
James Tursa on 27 Mar 2014
Edited: James Tursa on 27 Mar 2014
If n<0, then you get inside the "if" block to get a new n, but that path does not get into the "else" part of your code so no "ans" is produced. So take the "ans" part of the code out of the "else" block. E.g.,
function fact2=fact(n)
%function to write factorials
if n<1
disp('incorrect answer')
disp(' ')
n=input('Enter new value of n:')
end
ans=1;
while n>1
ans=ans*n;
n=n-1;
end
fact2=ans;
You might also consider changing your "if n<0" test to a "while n<0" test, and also to tell the user what is wrong instead of just saying that something is wrong. I.e., instead of 'incorrect answer', maybe 'input must be non-negative integer' (and maybe check to see that it is an integer)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!