if else nested loops
이전 댓글 표시
This is my program... i want the ouput of x and y to be the new values not the 0 and 0. this always returns me 0 and 0 why?
clc
clear
a=input('a')
b=input('b')
x=0;
y=0;
if a>b
x-1
y-1
else if a<b
x+1
x+2
else if a==b
y=1
x
end
end
end
x
y
답변 (1개)
A. Sawas
2019년 4월 8일
The problem is not with the if-else statments (although they are not correctly used). You need to assign the new values to x and y like this:
x - 1; % this does not change the values of x
x = x - 1; % the new value (x-1) is assigned to x
y = y - 1;
댓글 수: 7
A. Sawas
2019년 4월 8일
I guess this is what you are trying to do in a cleaner code:
clc;
clear;
a=input('a');
b=input('b');
x=0;
y=0;
if a>b
x = x-1;
y = y-1;
else if a<b
x = x+1;
y = y+2;
else % a==b this is the remaining case
y = 1;
end
disp(x);
disp(y);
Arouj
2019년 4월 8일
Walter Roberson
2019년 4월 8일
You would need another end on that code, unless you change the else if to elseif
A. Sawas
2019년 4월 8일
First, to find the issue in the result try to display the value of the variables and intermediate calculations. One easy and quick way is to highlight part of the equation and press F9 to evaluate and see the result.
Second, I suggest you use switch statement which is nicer to follow and code:
switch (RF)
case 'a'
% case 'a' code
case 'b'
% case 'b' code
case 'c'
% case 'c' code
otherwise
fprintf('No such case');
end
Arouj
2019년 4월 8일
Image Analyst
2019년 4월 8일
편집: Image Analyst
2019년 4월 8일
Sawas:
else if a<b
is much, much different than
elseif a<b
If you don't know why, just ask.
A. Sawas
2019년 4월 9일
Image Analyst: Thanks for the note ... I know that very well ;)
카테고리
도움말 센터 및 File Exchange에서 Programming에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!