loop problem with time delay
3 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
James Tursa
2017-10-6
编辑:James Tursa
2017-10-6
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.
0 个评论
更多回答(1 个)
DUY Nguyen
2023-3-2
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!