Frustrating for what should be simple… What have I done wrong?
1 回表示 (過去 30 日間)
古いコメントを表示
Here is an example of some simple code I have written. When I ask the user for a yes/no answer it works for yes but gives an error when they enter no (matrix dimensions do not agree). However it does work if the input is only a y or n. Why is this?
a = 'no';
while a ~= 'yes'
a = input('Do you like the colour red? (yes/no) ——> ','s');
if a == 'yes'
disp('Good its the best colour ever')
elseif a == 'no'
disp('Whats wrong with you?... TRY AGAIN')
else
disp('Thats not an answer, enter y for yes or n for no.')
end
end
THANKS!!
0 件のコメント
採用された回答
Paul
2014 年 2 月 15 日
編集済み: Paul
2014 年 2 月 15 日
For strings you shouldn't use == to compare but strcmp for case sensitive comparison or strcmpi for not case sensitive. So this code should work for you:
a = 'no';
while ~strcmpi(a,'yes')
a = input('Do you like the colour red? (yes/no) ——> ','s');
if strcmpi(a,'yes')
disp('Good its the best colour ever')
elseif strcmpi(a,'no')
disp('Whats wrong with you?... TRY AGAIN')
else
disp('Thats not an answer, enter y for yes or n for no.')
end
end
その他の回答 (2 件)
Azzi Abdelmalek
2014 年 2 月 15 日
編集済み: Azzi Abdelmalek
2014 年 2 月 15 日
Use
while ~isequal(a,'yes')
You can't compare 'yes' and 'no' using ==, try this
'abc'=='abf'
the result is a comparison character by character. The two strin must have the same number of characters
1 1 0
because the first two element are the same, but not the third. Now if you use
isequal('abc','abf')
the result is
0
because isequal compare the two string, there is no comparison character by character.
0 件のコメント
Jos (10584)
2014 年 2 月 15 日
編集済み: Jos (10584)
2014 年 2 月 16 日
Another option with strings is to use SWITCH-CASE-END in combination with a WHILE-loop and a BREAK statement. The big advantage using SWITCH over IF is that you can accept different answers
while (1)
a = input('Do you like the colour red? (yes/no) ——> ','s');
switch lower(a)
case {'yes','y','jawohl','yes sir yes','yes i do'}
disp('Good, it''s the best colour ever') % note the double quotes ...
break ; % Breaks out of the infinite while loop
case {'no','n','nope','no way man!','njet','i hate red'}
disp('What''s wrong with you?... TRY AGAIN')
otherwise
disp('That''s not an answer, enter y for yes or n for no.')
end
end
(Edited…Thanks Paul!)
2 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!