loop problem with time delay

9 visualizaciones (últimos 30 días)
Hayden O'Neil
Hayden O'Neil el 5 de Oct. de 2017
Respondida: DUY Nguyen el 2 de Mzo. de 2023
Write Matlab code using a loop structure that displays the following text to the command window: “Man, I am getting older and wiser by the second” And (after a carriage return) on the following line displays the phrase: “and now I am 1 second older”
And after waiting a full second in real time (approximate) increments and displays the phrase: “and now I am 2 seconds older” [Note that I want you to update the units on “second” to show correct number –second(s) ]
And after waiting a full second in real time (approximate) increments and displays the phrase: “and now I am 3 seconds older”
And so on and so on until 10 full carriage returns of textual display have been reached and the final line reads: “and Prof. Koz just wasted approximately blank seconds of my life”
I have no idea how to do this problem or delay output by one second for each line.

Respuesta aceptada

James Tursa
James Tursa el 6 de Oct. de 2017
Editada: James Tursa el 6 de Oct. de 2017
Hint: You could use tic and toc for this. Start your code with a tic statement. Then you can examine the toc result in a loop and take appropriate action (display a message, break out of the loop, etc). The toc result will be in seconds. E.g., experiment with the following code and see if you can modify it to do what you want.
time_delay = 5;
tic
while( true )
if( toc >= time_delay )
fprintf('It has been %f seconds\n',time_delay);
break;
end
end
Alternatively, you could look into using the pause() function, maybe with a for loop or something similar.

Más respuestas (1)

DUY Nguyen
DUY Nguyen el 2 de Mzo. de 2023
Hi Hayden,
Hope this code below could help you!
for i = 1:10
if (i==1)
fprintf('Man, I am getting older and wiser by the second\n');
fprintf('and now I am 1 second older\n', i);
else
fprintf('and now I am %d seconds older\n', i);
end
pause(1);
end
fprintf('and Prof. Koz just wasted approximately %d seconds of my life\n', i);

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by