フィルターのクリア

While or for loop?

2 ビュー (過去 30 日間)
Mark Coughlin
Mark Coughlin 2020 年 4 月 30 日
編集済み: Mehmed Saad 2020 年 4 月 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
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
Mehmed Saad 2020 年 4 月 30 日
  1. Use while loop
  2. instead of using if else and continue break in while(true), add condition in while loop
  3. Print after the while loop ends
PS: you need a break condition for a while(true) type loop otherwise it will continue runing forever
  7 件のコメント
Mark Coughlin
Mark Coughlin 2020 年 4 月 30 日
Thankyou very much Mehmed, your explanation was extremely informative and helpful. I realise the solution is a lot simplier than I initally thought. I got the code working.
num=input('Enter a number: ');
n=1;
while (f<=num)
n=n+1;
f=factorial(n);
end
formatSpec='The factorial greater than %d is %d';
fprintf(formatSpec,num,f);
Mehmed Saad
Mehmed Saad 2020 年 4 月 30 日
編集済み: Mehmed Saad 2020 年 4 月 30 日
Cheers.
Also when you ve problem in code apply break point approach first to detect problem as told by Rik.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by