【问题标题】:How can i make this simple for loop run every second? [closed]我怎样才能让这个简单的 for 循环每秒运行一次? [关闭]
【发布时间】:2021-07-06 12:23:23
【问题描述】:

这是一个简单的计时器,从用户设置的值开始倒计时到 0

namespace SuperSimpleTimer
{
    class Program
    {


        static void Main(string[] args)
        {
            //This makes the loop starts from a user inserted value
           myTime = int.Parse(Console.ReadLine());

            for (int i = myTime; i >= 0; i--)
            {
                // clears the old value and Writes the new one
                //Console.Clear();
                Console.WriteLine(i);

            }
            Console.ReadLine();

        }
    }
}

【问题讨论】:

  • System.Threading.Thread.Sleep(1000); 延迟 1 秒 - 但我认为这不是你真正想要发生的事情
  • 这能回答你的问题吗? Time delay in For loop in c#

标签: c# for-loop console


【解决方案1】:

最简单的方法是:

Thread.Sleep(1000);

这应该像这样应用:

using System.Threading;

namespace SuperSimpleTimer
{
    class Program
    {


        static void Main(string[] args)
        {
            //This makes the loop starts from a user inserted value
           myTime = int.Parse(Console.ReadLine());

            for (int i = myTime; i >= 0; i--)
            {
                // clears the old value and Writes the new one
                //Console.Clear();
                Console.WriteLine(i);
                Thread.Sleep(1000); //1000(ms) = 1 second

            }
            Console.ReadLine();

        }
    }
}

【讨论】:

  • 您还可以添加一些输入验证/检查(int.TryParse 的非整数,负值)以改进 OP 代码
  • 请记住,最简单的解决方案并不总是最好的解决方案。
猜你喜欢
  • 2022-12-18
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 2014-06-18
  • 2022-08-20
  • 2021-07-26
相关资源
最近更新 更多