如何在函数控制台中编写变量。在这种情况下写?

时间:2017-02-04 11:55:38

标签: c#

我正在学习c#以获得乐趣! 我有c编码的经验,我有一个非常愚蠢的问题,在我的控制台应用程序中,我想使用Console.Write显示一个名为“x”的变量,但我想在同一个函数中显示一个文本行。如果您不明白我在这里附上我所做的代码。

  using System;

namespace Media_Random
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.Write ("This program makes an avarage of 3 numbers chosen randomly\n");
            int a = 1;
            int b = 10;
            Random random = new Random();
            int x=random.Next(a,b);
            Console.Write ("the first value is\n",x); //i want to in write in the console the value x there but it doesn't work 
        }
    }

}

我希望通过显示代码来理解问题会更简单。

3 个答案:

答案 0 :(得分:1)

试试这个:

 Console.Write("the first value is {0}\n", x); 

请注意,您使用过载的Console.Write需要格式字符串,其中占位符适用于x{0} in背景。

进一步的建议:Console具有特殊方法WriteLine,这就是为什么你可能不想要放

 Console.Write("...\n");

而不是

 Console.WriteLine("...");

答案 1 :(得分:0)

如果您想这样做以这种格式显示它:

the first value is
X

然后使用此方法:

Console.Write(string.Format("the first value is\n{0}", x));

但是如果您希望以这种格式显示int:

the first value is X
<newlinehere>

然后使用此方法:

Console.WriteLine(string.Format("the first value is {0}\n', x));

如果你想以不同的方式格式化它,你应该read this

答案 2 :(得分:0)

还有一件事。如果您使用的是VS 2015,则可以使用$更改string.Format:

Console.WriteLine($"the first value is {x}");

在开放引号前添加$允许您直接将变量放在占位符中。从我的角度来看,这种语法更容易,更易读。