If statements inside while loop

20 ビュー (過去 30 日間)
Ben Hischar
Ben Hischar 2021 年 8 月 13 日
コメント済み: DGM 2021 年 8 月 13 日
Hi all,
im trying to write a script that has a while loop with conditional statements.
I am trying incoperate my if statements into the while loop so that if a input is above or below 20 and 0 it will display message.
i am not sure where the if statements are meant to be, inside the loop or outside.
here is my code an help would be appreciated.
clear all;
n=input('Which multiplication table? :');
n=input(prompt);
min_integer=0;
max_integer=20;
i=1;
while(i<=12)
if n < 0
message = 'Please enter number from 0 to 20.';
elseif n > 20
message = 'Please enter number from 0 to 20.';
end
fprintf('%dx%d=%d \n',n,i,n*i);
i=i+1;
end
Thanks

採用された回答

DGM
DGM 2021 年 8 月 13 日
編集済み: DGM 2021 年 8 月 13 日
Like this, if necessary.
% set up parameters and use them
max_k = 12;
min_input=0;
max_input=20;
nisbad = true;
while nisbad
% explain the inputs to the user
% nobody can guess what the limits are unless you tell them
disp('Which multiplication table?');
n=input(sprintf('Please enter number from %d to %d: ',min_input,max_input));
nisbad = n<min_input || n>max_input;
end
for k = 1:max_k
fprintf('%dx%d=%d \n',n,k,n*k);
end
I could say something about this style of bad design taught by introductory assignments, but I've said it enough times to know that it doesn't matter.
  2 件のコメント
Ben Hischar
Ben Hischar 2021 年 8 月 13 日
im confused by what you mean by your last comment
DGM
DGM 2021 年 8 月 13 日
Don't take that the wrong way. I'm assuming this was homework. I'm just at odds with certain things instructors ask students to do in their homework assignments. I had to do the same things too.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by