Need help on a problem

Hi, everyone!
For one of my homework problems, I am asked to create a script that asks for an even integer. When the even number is inserted, the script will print out the number and stop. However, it will keep asking for an input if the number given isn't even. The script should work like this:
>>Q3Script
Enter an even integer: 9
9 is not an even integer. Try again: -7
-7 is not an even integer. Try again: 4 Thanks, 4 is a correct even integer.
This is what I have so far:
prompt='Enter an even integer: ';
X=input(prompt);
if rem(X,2)==0
fprintf('Thanks, %0.1f is a correct even integer\n',X);
else
input('%.1f is not an even integer. Try again: ', X);
end
I am just confused on how to make the script loop back around once the incorrect integer is inserted, and I would appreciate any help I can get on improving this script. Thanks in advance!

回答 (2 件)

Voss
Voss 2022 年 10 月 26 日

0 投票

In a situation like this, where you have to repeat an operation a number of times but you cannot predict how many, it's convenient to use a while loop:
prompt = 'Enter an even integer: ';
X = input(prompt);
while rem(X,2) ~= 0
X = input(sprintf('%.1f is not an even integer. Try again: ', X));
end
fprintf('Thanks, %0.1f is a correct even integer\n',X);
David Hill
David Hill 2022 年 10 月 26 日

0 投票

You need a while loop.
x=input('Enter an even integer: ');
while mod(x,2)==1
x=input(sprintf('%.1f is not an even integer. Try again: ',x));
end
fprintf('Thanks, %0.1f is a correct even integer\n',x);

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2022 年 10 月 26 日

回答済み:

2022 年 10 月 26 日

Community Treasure Hunt

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

Start Hunting!

Translated by