簡體   English   中英

無法將字符串數組正確轉換為雙精度數組,返回0

[英]Can't convert string array to double array properly, returns 0

在上面的代碼中,我試圖將通過從文本文件中讀取所有行而制成的字符串數組轉換為雙精度數組。 但是,當我這樣做時,我打印出雙精度數組中的每個數字,它們都打印出來,說

  0  
  0  
  0  
  0

在文件中時,實際數字為:

  -0.055
  -0.034      
  0.232      
  0.1756

我不明白為什么要這么做,我們將不勝感激。

您不Parse文件中的值。 應該是這樣的:

 double[] test = System.IO.File
   .ReadLines(new_path)
   .Select(line => double.Parse(line)) // <- each line should be parsed into double
   .ToArray();

 foreach (double number in test) {
   Console.WriteLine(number);
 }         

 Console.ReadLine();

您實際上從未向test數組添加任何值。 這行代碼:

double[] test = new double[numberArray.Length];

只是說創建一個x大小的空白數組。 該數組內的值是默認值( double的默認值是0 )。 如果希望它們存在,則需要為數組分配值。

將文本文件行轉換為雙精度數組的最簡單方法是使用一點Linq:

if(File.Exists(newPath))
{
    double[] test = File.ReadLines(newPath).Select(x => double.Parse(x)).ToArray()
    foreach(double number in test)
    {
        Console.WriteLine(number);
    }         
    Console.ReadLine();
}

的缺點是沒有錯誤處理。

如果您想對錯誤進行處理,則代碼會稍長一些,應該創建一個ParseLines()方法:

double[] test = ParseLines(newPath).ToArray()
foreach(double number in test)
{
    Console.WriteLine(number);
}         
Console.ReadLine();

private static IEnumerable<double> ParseLines(string filePath)
{  
    if(File.Exists(newPath))
    {
        foreach(string line in File.ReadLines(newPath))
        {
            double output;
            if(double.TryParse(line, out output))
            {
                yield return output;
            }
        }
    }
}

這里有一些很好的答案。 這是沒有Linq的另一個答案:

double parsedNumber;
for (int i = 0; i < numberArray.Length; i++)
{
    bool numberIsValid = double.TryParse(numberArray[i], out parsedNumber);

    if (numberIsValid)
        test[i] = parsedNumber; 
    else
        Console.WriteLine($"{numberArray[i]} is not a valid double.");
}

暫無
暫無

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

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