How to use not equal to '~=' operator in if statement?
745 次查看(过去 30 天)
显示 更早的评论
My code works fine with '==' but not with '~='.I expect it not to display 'error' if user enters A or B
x=input('input x','s')
if(x~='A')||(x~='B')
disp('error');
end
0 个评论
采纳的回答
John D'Errico
2017-2-21
编辑:John D'Errico
2017-2-21
A problem of elementary logic?
You want an error to return only if A is not in the set {'A','B'}. So a call to ismember might be a good alternative.
Regardless, given the approach you have followed, if x is equal to 'A', then the second half of the clause will be true, even though the first part of the clause is false. And the logical statement
false || true
is TRUE.
You are asking for a result that is only true when BOTH parts of the clause are true. Use a logical and, NOT a logical or.
if(x~='A') && (x~='B')
0 个评论
更多回答(2 个)
Jan
2017-2-21
Remember, that the negation of
(x=='A') || (x=='B')
is:
~((x == 'A') || (x == 'B')) ==>
~(x == 'A') && ~(x == 'B') ==>
(x ~= 'A') && (x ~= 'B')
2 个评论
Walter Roberson
2017-11-28
if any((x ~= 'a') & (x ~= 'p') & (x ~= 'T'))
fprintf('ERROR:You entered incorrect choice.')
end
or
if ~all( ismember(x, {'a', 'p', 'T'}) )
fprintf('ERROR:You entered incorrect choice.')
end
另请参阅
类别
Find more on Source Control Integration in Help Center and File Exchange
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!