While or for loop?
2 次查看(过去 30 天)
显示 更早的评论
Hi, I want to write a script which will evaluate the lowest factorial which is greater than the user's input, and I am unsure of whether to use a while or a for loop to execute this. Any help is always much appreciated! This is my code so far:
num=input('Enter a number: ');
n=0;
while (true)
n=n+1;
f(1i)=factorial(n);
if f(1i)>num
formatSpec='The factorial greater than %d is %d';
fprintf(formatSpec,num,f);
else
continue
end
end
1 个评论
Guillaume
2020-4-30
Typically, you'd use a while loop if you don't know in advance how many times you're going to loop, and a for loop if you do. Therefore in your case, a while loop would be more appropriate.
However, note that you can always convert one to the other.
采纳的回答
Mehmed Saad
2020-4-30
- Use while loop
- instead of using if else and continue break in while(true), add condition in while loop
- Print after the while loop ends
PS: you need a break condition for a while(true) type loop otherwise it will continue runing forever
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!