[英]c# Console.WriteLine();
在 C# 中,在我編寫Console.WriteLine()
並且我被要求輸入多個值后,我可以用一種方法獲取它們嗎? 例如:
double a, b, c = 0;
Console.WriteLine("please enter the values of:\n a value:\n b value: \n c value:");
謝謝您的幫助 (:
沒有針對此特定功能的 BCL 方法,但您可以使用輔助函數來收集這些內容,而無需過多重復。
static void Main(string[] args)
{
string RequestInput(string variableName)
{
Console.WriteLine($"{variableName}:");
return Console.ReadLine();
}
Console.WriteLine("please enter the values of:");
var a = double.Parse(RequestInput("a"));
var b = double.Parse(RequestInput("b"));
var c = double.Parse(RequestInput("c"));
}
您可以執行以下操作,假設用戶將在控制台中輸入一個字符串,例如"2.3 3.4 4.5"
。 您可能需要進行一些檢查以確保輸入正確。
double a = 0.0, b = 0.0, c = 0.0;
Console.WriteLine("please enter the values of: a b c");
string input = Console.ReadLine();
string[] inputParts = input.Split(' ');
if (inputParts.Length > 0 && inputParts[0] != null)
{
Double.TryParse(inputParts[0], out a);
}
if (inputParts.Length > 1 && inputParts[1] != null)
{
Double.TryParse(inputParts[1], out b);
}
if (inputParts.Length > 2 && inputParts[2] != null)
{
Double.TryParse(inputParts[2], out c);
}
Console.WriteLine($"a: {a.ToString()}");
Console.WriteLine($"b: {b.ToString()}");
Console.WriteLine($"c: {c.ToString()}");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.