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
2022-10-26
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
2022-10-26
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!