IF else stement with Logical OR operator problem

I was writing a program use logical OR operator in If else . I used following code:-
grade=input('enter grade of the student \n', 's');
if grade=='A'|'B'
fprintf('student''s grade is %c. excellent Job \n',grade);
elseif grade=='C'
fprintf('student''s grade is %c. well done \n',grade);
elseif grade=='D'
fprintf('student''s grade is %c. Try harder\n',grade);
else
fprintf('Invalid entry\n');
end
irrespective of what is enter, always it shows " student's grade is X . excellent Job". Matlab is not processing any else if conditions.
Kindly provide insight

 Respuesta aceptada

KSSV
KSSV el 19 de Jul. de 2020
Editada: KSSV el 19 de Jul. de 2020
You should use
strcmp(grade,'A') || strcmp(grade,'B')
Check the code:
grade=input('enter grade of the student:', 's');
if (strcmp(grade,'A') || strcmp(grade,'B'))
fprintf('student''s grade is %c. excellent Job \n',grade);
elseif strcmp(grade,'C')
fprintf('student''s grade is %c. well done \n',grade);
elseif strcmp(grade,'D')
fprintf('student''s grade is %c. Try harder\n',grade);
else
fprintf('Invalid entry\n');
end

4 comentarios

T P Ashwin
T P Ashwin el 19 de Jul. de 2020
thanks a lot KSSV for prompt answer.the code worked.
Could you explain why the OR logic was not functioning with string values?I just wanted to understand the reason behind it.
KSSV
KSSV el 19 de Jul. de 2020
It suggested to use strcmp when you check whether two strings are equal or not.
Bruno Luong
Bruno Luong el 19 de Jul. de 2020
Editada: Bruno Luong el 19 de Jul. de 2020
Could you explain why the OR logic was not functioning with string values?
This is the "problem" of computer language, which is radical different (and arguably more logic) than human laguage.
When you (a human) read/write
grade=='A'|'B'
I believe you simply translate from human laguage
If the grade is 'A' or 'B'.
BUT the computers understand this expresion like this:
grade == ('A' | 'B') % priority of operator
('A' | 'B') is logical operator so it translates to
'A'>0 | 'B'>0
So it translate using ascii code (computer manipulates only numbers) of the chararter
65>0 | 64>0
which returns always TRUE,
meaning equivalent to
1
in computer language (remember. computer manipulates numbers and nothing else).
So you expression
grade=='A'|'B'
is interpreted by MATLAB as
grade==1
!!! Actually it inturns then translate to ascii equivalent to something like
grade == 'some strangle grade that the is not in human world'
Now this is nowhere equivalent to what you (human) think
grade equal to 'A' or 'B'
T P Ashwin
T P Ashwin el 19 de Jul. de 2020
Thanks. Nice explaination. Veey well explained

Iniciar sesión para comentar.

Más respuestas (0)

Preguntada:

el 19 de Jul. de 2020

Comentada:

el 19 de Jul. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by