While loop and arrays

2 visualizzazioni (ultimi 30 giorni)
Tuna KISAAGA
Tuna KISAAGA il 23 Apr 2021
Commentato: DGM il 23 Apr 2021
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 Commento
DGM
DGM il 23 Apr 2021
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.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by