# Where is the issue in my "while" statement?

조회 수: 4 (최근 30일)
Geo 2017년 7월 29일
답변: Teja Muppirala 2017년 7월 30일
I want to evaluate the first integer evenly divisible by 3 and 5 using a Matlab code. My attempt is the following:
n=1;
while mod(n,5)~=0 && mod(n,3)~=0
n=n+1;
end
n
I'm new to Matlab and wondering where the issue here is. The code returns n=3 for some reason. I also want to extend this to find the first number evenly divisible by 1-10, for which I wrote the following while loop which also did not return the expected value. Where is my error?
n=1;
while mod(n,1:10)~=0
n=n+1;
end
n
Thank you.
##### 댓글 수: 3이전 댓글 1개 표시이전 댓글 1개 숨기기
Geo 2017년 7월 29일
편집: Geo 2017년 7월 29일
Revision also not working as expected:
n=1;
for k=1:10
while mod(n,k)~=0
n=n+1;
end
end
n
Walter Roberson 2017년 7월 29일
found_solution = false;
n = 0;
while ~found_solution
n = n + 1;
found_solution = true;
for k = 1 : 10
if mod(n,k) ~= 0
found_solution = false;
break;
end
end
end
n

댓글을 달려면 로그인하십시오.

### 답변 (2개)

the cyclist 2017년 7월 29일
편집: the cyclist 2017년 7월 29일
In your second case, you are doing
mod(1,1)
then
mod(2,2)
then
mod(3,3)
and so on, because you are always incrementing n right along with k. Those mod functions are always equal to zero, so they always satisfy the while condition, so you get to n = 10.
##### 댓글 수: 0이전 댓글 -2개 표시이전 댓글 -2개 숨기기

댓글을 달려면 로그인하십시오.

Teja Muppirala 2017년 7월 30일
You were on the right track. This gives 2520:
n=1;
while any( mod(n,1:10)~=0 )
n=n+1;
end
n
When your conditional has more than one element, all of them must be true for it to evaluate as true. This will return 'B' and 'C'.
if [1 1 1 0]
disp('A')
else
disp('B')
end
if [1 1 1 1]
disp('C')
else
disp('D')
end

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Graphics Object Programming에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by