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!

Antworten (2)

Voss
Voss am 26 Okt. 2022

0 Stimmen

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 am 26 Okt. 2022

0 Stimmen

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);

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Tags

Gefragt:

am 26 Okt. 2022

Beantwortet:

am 26 Okt. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by