~ operator in while not working as intended

2 vues (au cours des 30 derniers jours)
Sneha Chakravarthy le 5 Avr 2021
I have this piece of code to make sure that the input is a whole number between 1 and 12
while (x~=1 || x~=2 || x~=3 || x~=4 || x~=5 || x~=6 || x~=7 || x~=8 || x~=9 || x~=10 || x~=11 || x~=12)
fprintf("\nOption entered is not present in the menu. Please enter a valid number");
x = input("\nEnter number corresponding to the conversion you want to perform: ");
end
However, the loop prints out the error message even the input is correct. Why is that so?
2 commentairesAfficher AucuneMasquer Aucune
Stephen23 le 5 Avr 2021
"Why is that so?"
Flawed logic. Can you name any value for which
x~=1 || x~=2
will return false?
Sneha Chakravarthy le 6 Avr 2021
Oh dear, it is quite obvious isn't it. Thanks for the help

Connectez-vous pour commenter.

Réponses (2)

Mike le 5 Avr 2021
In your code the or condition ( || ) ensures it always executes the error. You need to do a logical and i.e. change all || to &&.
0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Steven Lord le 5 Avr 2021
Let's take a simpler example.
check = @(x) (x ~= 1) | (x ~= 2)
check = function_handle with value:
@(x)(x~=1)|(x~=2)
Does this return true for 1.5?
check(1.5)
ans = logical
1
Does it return true for 3?
check(3)
ans = logical
1
Does it return true for 1?
check(1)
ans = logical
1
Whoops. Why? Well, 1 is equal to 1 so (x ~= 1) returns false. But 1 is not equal to 2 so (x ~= 2) returns true. And false or true returns true.
For something like this, you could use round (to make sure x is an integer value) and > and < to determine if it's in the bounds that you want. Alternately, if you want to limit x to being in a specific set of values use ismember.
0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

Catégories

En savoir plus sur Numeric Types dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by