how to write a sript for while loop and for loop. please include code

15 次查看(过去 30 天)
Write a script that first asks the user for a number (using the input command).
Using an if statement, print out if this number is positive, negative or zero. Test
your script a few times to make sure it does the right thing for all three cases.
o Put a break point in each branch of the if statement
o Run the script and enter a negative number. Did you stop at the right
branch? If so, un-click that break point. Repeat with a positive number and
with zero to check that you visit all three if statement branches.
Now copy your if statement and put it in a for loop that asks the user for input 10
times so you don’t have to keep calling the script by hand. Remember that
control-c will stop the loop.
Now change the for loop to a while loop that stops when the user inputs zero.
What should your stopping condition be?
o Hint: There are two ways to do this. One is to declare a “flag” variable that
is set to false before you start the while loop, eg stop = 0; while stop ==
0When you get an input that is zero, set stop to be true.
o Second approach: Suppose you are using n as the variable you store the
users input in (eg n = input(‘Type a number’)). Declare n before the start
of the while loop, setting it to some value other than zero. Then, check the
value of n.

采纳的回答

ES
ES 2013-10-15
Homework ain't it?
InputNumber=input('enter the number');
%Do some checjks to validate if the input is valid here
if InputNumber>0
disp('Positive Number');
elif InputNumber<0
disp('Negative Number');
else
disp('Zero');
end
II
for loop1=1:10
nputNumber=input('enter the number');
%Do some checjks to validate if the input is valid here
if InputNumber>0
disp('Positive Number');
elif InputNumber<0
disp('Negative Number');
else
disp('Zero');
end
end
III
InputNumber=1;
while (loop1<10 && InputNumber~=0)
InputNumber=input('enter the number');
%Do some checjks to validate if the input is valid here
if InputNumber>0
disp('Positive Number');
elif InputNumber<0
disp('Negative Number');
end
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by