While loop - Factorial

82 次查看(过去 30 天)
Gyp
Gyp 2020-1-31
评论: Rik 2020-1-31
The problem I have is that when I write a negative number, I want what I set out to come out. When I do it for the first time it works and I can re-enter a number. But when for the second time I put a negative number (to prove that it works) the program prints an incorrect number, instead of asking again to put a new number (not negative).
Ex. I put -1 and get: "n = input ('The factorial function is defined for non-negative integers only.Enter a non-negative number:').
If I try to put -1 again, the factorial number of -1 is 1.
How can I correct it to keep asking for a new number as long as they put a negative one?
Thanks
Screenshot (331).png
  1 个评论
Rik
Rik 2020-1-31
Next time, post code instead of an image, and add the tag homework if you post homework.

请先登录,再进行评论。

回答(1 个)

Rik
Rik 2020-1-31
You need to repeat the exact same code until some condition is true. The easiest way to do that is with a while loop:
n=-1;%set initial input to something invalid to enter the loop
while %check input
%if input is invalid, repeat input
end
%now calculate the factorial
  2 个评论
Rik
Rik 2020-1-31
Comment posted as answer by Gyp:
Hi Rick, i think i'm doing that. I have the "while" code for positive numbers only.
But when a put a negative number, just to verify, this give me a results... I don't want the program to give me a result when a negative number is written. I just want the program to ask for a number again.
Rik
Rik 2020-1-31
You aren't doing that. You should be separating the two tasks (getting the input and calculating the factorial). What you showed in your question is not doing that. Try filling in what I wrote above:
n=-1;%set initial input to something invalid to enter the loop
while %check input
%if input is invalid, repeat input
end
%now calculate the factorial
%%% here the code goes that actually calculates the factorial
That means your final code will contain two while loops.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by