Borrar filtros
Borrar filtros

how do I convert this to a for loop

1 visualización (últimos 30 días)
Nicholas Repko
Nicholas Repko el 14 de Abr. de 2020
Respondida: Peng Li el 14 de Abr. de 2020
x = input('Enter a number between 1 and 100: ');
i = 0;
while x>0
x=x-i;
i=i+1;
end
fprintf('The while loop ran for %d interations\n' ,i)

Respuesta aceptada

Peng Li
Peng Li el 14 de Abr. de 2020
% your while loop
x = input('Enter a number between 1 and 100: ');
i = 0;
while x>0
x=x-i;
i=i+1;
end
fprintf('The while loop ran for %d interations\n' ,i)
% my for loop
x = input('Enter a number between 1 and 100: ');
for i = 0:100
x = x - i;
if x <= 0
break;
end
end
fprintf('The while loop ran for %d interations\n', i + 1)
Enter a number between 1 and 100: 30
The while loop ran for 9 interations
Enter a number between 1 and 100: 30
The while loop ran for 9 interations

Más respuestas (1)

David Hill
David Hill el 14 de Abr. de 2020
Don't understand the purpose of the loop.
x = input('Enter a number between 1 and 100: ');
for i=1:x
end
fprintf('The for loop ran for %d interations\n' ,x)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by