无法将字符串数组正确转换为双精度数组,返回0

时间:2018-07-23 14:11:07

标签: c# arrays file

在上面的代码中,我试图将通过从文本文件中读取所有行而形成的字符串数组转换为双精度数组。但是,当我这样做时,我打印出双精度数组中的每个数字,它们都打印出来,说

  0  
  0  
  0  
  0

文件中的实际数字为:

  -0.055
  -0.034      
  0.232      
  0.1756

我不明白为什么要这么做,将不胜感激。

3 个答案:

答案 0 :(得分:4)

You don't Parse values from the file. It should be something like this:

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

答案 1 :(得分:0)

You never actually add any values to your test array. This line of code:

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

Is just saying create a blank array, of x size. The values inside that array with be the default (the default of double is 0). You need to assign values to the array if you want them to be there.

The easiest way to do convert your text file lines to a double array would be to use a little 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();
}

The has the drawback of having no error handling though.

If you want to have error handling your code will just be a little longer, and you should create a ParseLines() method:

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

答案 2 :(得分:0)

这里有一些很好的答案。这是没有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.");
}