C# 在 .net 控制台应用程序中显示百分比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1379455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:51:23  来源:igfitidea点击:

showing percentage in .net console application

c#.netconsole-application

提问by Ronnie Overby

I have a console app that performs a lengthy process.

我有一个控制台应用程序,它执行一个漫长的过程。

I am printing out the percent complete on a new line, for every 1% complete.

我在新行上打印完成百分比,每完成 1% 完成

How can I make the program print out the percent complete in the same location in the console window?

如何让程序在控制台窗口的同一位置打印完成百分比?

采纳答案by Jon Skeet

Print \rto get back to the start of the line (but don't print a newline!)

打印\r回到行首(但不要打印换行符!)

For example:

例如:

using System;
using System.Threading;

class Test
{
    static void Main()
    {
        for (int i=0; i <= 100; i++)
        {
            Console.Write("\r{0}%", i);
            Thread.Sleep(50);
        }
    }
}

回答by Noon Silk

You may use:

您可以使用:

Console.SetCursorPosition();

To set the position appropriately.

适当地设置位置。

Like so:

像这样:

Console.Write("Hello : ");
for(int k = 0; k <= 100; k++){
    Console.SetCursorPosition(8, 0);
    Console.Write("{0}%", k);
    System.Threading.Thread.Sleep(50);
}

Console.Read();