簡體   English   中英

我該如何在功能控制台中編寫可變性?在這種情況下寫?

[英]How can i write a variabile in the Function Console.Write in this case?

我正在學習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 
        }
    }

}

我希望顯示代碼可以更簡單地理解問題。

嘗試這個:

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

請注意,您使用的重載Console.Write希望在上下文中使用帶占位符x 格式字符串{0}

進一步的建議: Console具有WriteLine作為特殊方法,這就是為什么您可能不想放

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

代替

 Console.WriteLine("...");

如果要執行此操作以以下格式顯示:

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));

如果要以其他方式設置格式,則應閱讀本手冊

還有一件事。 如果您使用的是VS 2015,則可以使用$更改string.Format,如下所示:

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

在開放引號前添加$可以使您將變量直接放在占位符內。 從我的角度來看,此語法更容易理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM