Factorial code, stuck for some reason, help!

조회 수: 1 (최근 30일)
Praketa
Praketa 2014년 3월 27일
편집: James Tursa 2014년 3월 27일
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!

답변 (1개)

James Tursa
James Tursa 2014년 3월 27일
편집: James Tursa 2014년 3월 27일
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)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by