在Console.WriteLine中传递值

时间:2017-05-29 17:20:55

标签: c# console.writeline

以下是我正在处理的一段代码

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the number to find factorial : ");
        var fac = Convert.ToInt32(Console.ReadLine());
        var res = 1;
        for (var i = fac; i >= 1; i--)
        {
            res = res * i;
        }
        Console.WriteLine("Count of " + fac + " is : " + res);
    }
}

我想在结果中添加用户输入的输入fac。这里使用Console.WriteLine("Count of " + fac + " is : " + res);在我的控制台中显示输出。

我试过像

这样的东西
Console.WriteLine("Count of {0} is : {1} ", fac, res);

有更好的方法可以做到这一点,或者这很好......

3 个答案:

答案 0 :(得分:4)

另一种解决方案是使用string interpolation

Console.WriteLine($"Count of {fac} is : {res}");

答案 1 :(得分:1)

Console.WriteLine("Count of {0} is : {1} ", fac, res);overload of Console.WriteLine,支持格式字符串。

如果您需要使用值(例如fac,res)填充字符串模板(例如“{0}的计数为:{1}”),您还可以使用字符串插值(.net 4.6)或String.Format method使用重载也可以更轻松地使用重复值填充模板(例如String.Format("{0}-{1} {0}-{1} {2}", 1,2,3);

string s = String.Format("Count of {0} is : {1} ", fac, res);
Console.WriteLine(s);

答案 2 :(得分:1)

我避免使用加法运算符,因为它可能导致意外结果;例如

int a = 1;
int b = 2;
Console.WriteLine("hello world " + a + b);
//hello world 12
Console.WriteLine(a + b + " hello world");
//3 hello world

两条线看起来好像产生类似的输出,只有一条线开始hello world&另一个以此结束。但是,第一个示例("1" + "2")中字符串的数字成分为12,而第二个示例中的数字成分为3 1 + 2

@Aominè's answer最好,因为它非常清晰可读。 您也可以使用此技术应用格式;即。

Console.WriteLine("hello world {a:0.00} {b}");
//hello world 1.00 2

注意:数字占位符也可以使用格式化选项:

Console.WriteLine("hello world {0} {1:0.00}", a, b);
//hello world 1 2.00

在插值中使用数字占位符是有意义的时间是在定义变量之前需要定义格式。 e.g。

public class MyClass 
{
    const string MyStringFormat = "hello {0} world {1}";    
    public static string WriteMessage(int a, int b)
    {
        Console.WriteLine(MyStringFormat, a, b);
    }
}