While loop and arrays

조회 수: 2 (최근 30일)
Tuna KISAAGA
Tuna KISAAGA 2021년 4월 23일
댓글: DGM 2021년 4월 23일
I wanted to create a loop and store the values of "secsum" until the value of it is equal to "firstsum" or 7. But it doesn't work :( What do you think is wrong with it?
firstsum = floor(rand*6+1) + floor(rand*6+1);
j=1;
while j>=1
secsum(j) = floor(rand*6+1) + floor(rand*6+1);
if (secsum(j)==firstsum)
fprintf('You WIN with the sequence: %.0f %.0f',firstsum,secsum);
j=0;
elseif (secsum(j)==7)
fprintf('You LOSE with the sequence: %.0f %.0f',firstsum,secsum);
j=0;
else
j=j+1;
end
end
  댓글 수: 1
DGM
DGM 2021년 4월 23일
secsum is a vector, so either exit condition will produce multiple lines. If you only want to print the last result of secsum, just do
fprintf('You WIN with the sequence: %.0f %.0f\n',firstsum,secsum(j));
If you want to print the whole secsum vector, you can try using mat2str or some other method to get it into the output string.

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by