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

 採用された回答

KSSV
KSSV 2020 年 7 月 19 日
編集済み: KSSV 2020 年 7 月 19 日

0 投票

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 件のコメント

T P Ashwin
T P Ashwin 2020 年 7 月 19 日
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 2020 年 7 月 19 日
It suggested to use strcmp when you check whether two strings are equal or not.
Bruno Luong
Bruno Luong 2020 年 7 月 19 日
編集済み: Bruno Luong 2020 年 7 月 19 日
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 2020 年 7 月 19 日
Thanks. Nice explaination. Veey well explained

サインインしてコメントする。

その他の回答 (0 件)

質問済み:

2020 年 7 月 19 日

コメント済み:

2020 年 7 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by