error checking wont replace old input

1 次查看(过去 30 天)
This is my code and I want to error check it for the person to input a vector of grades that are from 0 to ten. Every time I run it once with the correct grades [1 2 3], it works. However, if I run it with a wrong vector [-1 2 3] then a correct one [1 2 3], it keeps telling me to enter another vector. I checked my workspace and it appears that the first vecgrade isnt being replaced by the second one.
clear all; clc
vecgrade=input('Enter a vector of quiz grades: \n');
vecchecker=vecgrade>=0 & vecgrade<=10;
while all(vecchecker)==0
vecgrade=input('Please enter another vector of quiz grades: \n');
vecchecker=vecgrade<0 & vecgrade>10;
end
vecgrade

采纳的回答

Geoff Hayes
Geoff Hayes 2014-11-16
David - your re-initialization of vecchecker in the while loop uses a different condition than the one outside of the while loop. Note that if
vecgrade = [1 2 3];
vecchecker=vecgrade<0 & vecgrade>10;
then
vecchecker =
0 0 0
Which makes sense because the condition is saying if the grade is less than zero and greater than ten - which is impossible, so the vector is all zeros (false).
Change your re-initialization of this local variable to be the same as that outside of the loop
vecchecker=vecgrade>=0 & vecgrade<=10;
and your code should work fine.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by