控制程序的输出
我正在编写一个代码来用 C++ 输出斐波那契数列,这很简单,但是由于我是编程新手,我正在考虑控制方法
我想知道是否有一种方法可以控制输出的时间,而无需包括处理时间(例如,如果需要 0.0005 秒来处理我的输入,并且我希望它在 1 秒而不是 1.0005 秒内重复输出)。
我还想知道是否有一种方法可以让它输出(比如1),然后让它等待我按回车键,这将使它输出第二部分(2)。
另外,我很感激有关如何控制输出的任何其他建议。
I'm writing a code to output fibonacci series in C++, which is simple enough, but since I'm new to programming, I'm considering ways to control
I was wondering if there's a way to control time for when outputs come out without processing time being included (e.g. If it takes .0005 seconds to process my input and I want it to repeat the output in 1 second rather than 1.0005 seconds).
I also am wondering if there's a way to just have it output (say 1) and then have it wait for me to press enter, which will make it output the second part (2).
Also, I'd appreciate any other suggestions on how to control output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用的是 Windows,一种快速暂停的方法是调用
system("pause");
但这并不是一种非常专业的处理方式。使用 std 命名空间暂停的一种方法是这样的:
至于你的主要问题......如果你只是处理向用户输出的文本,他们不可能注意到五微秒的延迟。但是,他们可以注意到您的间隔长度是否波动数十毫秒。这就是
sleep(..)
函数有时会失败的原因。让我们以想要每秒输出一次斐波那契数列中的另一个数字为例。这会很好地工作:
在等待之前计算序列中的下一个数字并准备好打印,因此计算时间不会给定时输出增加任何延迟。
如果您希望程序在后台运行时继续以固定速率输出,则需要查看进入线程。您可以将结果添加到一个线程中的队列中,而另一个线程检查结果以每秒打印一次。
If you're on Windows, a quick way to pause is to call
system("pause");
This isn't a very professional way of doing things, however.A way to pause with the std namespace would be something like this:
As for your main question... If you're just dealing with text output to the user, it's not possible for them to notice a five microsecond delay. They can notice if your interval lengths fluctuate by tens of milliseconds, however. This is why
sleep(..)
functions sometimes fail.Let's take your example of wanting to output another number in the Fibonacci sequence once per second. This will work just fine:
The next number in the sequence is computed and ready to print prior to the wait, thus the computation time will not add any delay to the timed output.
If you want your program to continue outputting at a fixed rate while your program works in the background, you'll need to look into threads. You can have your results added to a queue in one thread, while another thread checks for results to print once per second.