[英]How do I convert split string (string array) to double in C#?
問題:
正在檢查8個孩子的身高,並插入。
將8個雙精度值插入控制台,並制作算法以找出最低高度和最大高度。
所以這就是我所做的:
class work1 {
public static void Main(String[] args) {
string[] height = Console.ReadLine().Split(' ');
double[] heightInDouble = new Double[height.Length];
for (int i = 0; i <= height.Length; i++) {
heightInDouble[i] = (double) height[i]; // line 20
}
Console.WriteLine("Highest: " + heightInDouble.Max() + " Lowest: " + heightInDouble.Min());
}
}
結果:
錯誤:無法將類型'string'轉換為'double'(20)
如何將字符串轉換為double值 ?
你不能直接從字符串轉換為double。 使用double.Parse
:
realInts[i] = double.Parse( ints[i] );
您可能還想使用TryParse
,因為這里不確定該字符串實際上是一個數字:
double parsedValue;
realInts[i] = double.TryParse(ints[i], out parsedValue) ? parsedValue : 0;
還有一點需要注意:您可以使用Linq表達式鏈簡化語法:
double parsedVal;
double[] realInts = Console.ReadLine().Split(' ')
.Select(str => double.TryParse(str, out parsedVal) ? parsedVal : 0)
.ToArray();
嘗試這個。
static void Main(string[] args)
{
string[] ints = Console.ReadLine().Split(' ');
double[] realInts = new Double[ints.Length];
for (int i = 0; i <= ints.Length; i++)
{
double val;
if (Double.TryParse(ints[i], out val))
{
realInts[i] = val; // line 20
}
else
{
// Unable to parse
realInts[i] = 0;
}
}
}
使用此代碼
class work1
{
public static void Main(String[] args)
{
string[] height = Console.ReadLine().Split(' ');
double[] heightInDouble = new Double[height.Length];
for (int i = 0; i < height.Length; i++)
{
heightInDouble[i] = Convert.ToDouble(height[i]); // line 20
}
Console.WriteLine("Highest: " + heightInDouble.Max() + " Lowest: " + heightInDouble.Min());
Console.ReadLine();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.