While Loops for random numbers

12 ビュー (過去 30 日間)
Jeremy Hawk
Jeremy Hawk 2021 年 7 月 12 日
編集済み: John D'Errico 2022 年 8 月 23 日
Hi, I was given this assignment and wasn't sure how to set up the loop.
"Write a "while" loop that continues generating a random number x until x is less than 0.01. Keep track of how many iterations of the loop occurred. Then, use "fprintf" to print the final iteration count to the command window, along with the last value of x."
Thanks.
  8 件のコメント
John D'Errico
John D'Errico 2022 年 8 月 7 日
@Jeremy Hawk - Try being civil. I removed the nasty comment from your question.
Rena Berman
Rena Berman 2022 年 8 月 23 日
(Answers Dev) Restored edit

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

採用された回答

Image Analyst
Image Analyst 2021 年 7 月 12 日
Try this - it's a start:
loopCounter = 0;
maxIterations = 10000; % Failsafe. A number of iterations which you think you should never exceed.
x = inf; % Initialize
while x >= 0.01 && loopCounter < maxIterations
% Get new x (code for you to do...)
% Increment loop counter
loopCounter = loopCounter + 1;
end
fprintf('.......to do', ....)
The failsafe is not strictly required but you should always use one. I can't tell you how many times people write in and say they have a hung or infinite loop and it could be avoided if they had just used a failsafe.
  1 件のコメント
Jan
Jan 2022 年 8 月 7 日
Inspite of the vivid discussion, I'm the only one who voted for this useful answer. Because it matchs the question without posting a solution of a homework question, I select it as accepted answer.

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

その他の回答 (0 件)

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by