Factorial code, stuck for some reason, help!
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
0 Kommentare
Antworten (1)
James Tursa
am 27 Mär. 2014
Bearbeitet: James Tursa
am 27 Mär. 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)
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!