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

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


  0  

  0  

  0  

  0

在文件中时,实际数字是:


  -0.055

  -0.034      

  0.232      

  0.1756

我不明白为什么要这样做,任何帮助将不胜感激。


莫回无
浏览 228回答 3
3回答

慕尼黑8549860

你没有Parse从文件中取值。它应该是这样的:&nbsp;double[] test = System.IO.File&nbsp; &nbsp;.ReadLines(new_path)&nbsp; &nbsp;.Select(line => double.Parse(line)) // <- each line should be parsed into double&nbsp; &nbsp;.ToArray();&nbsp;foreach (double number in test) {&nbsp; &nbsp;Console.WriteLine(number);&nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;Console.ReadLine();

长风秋雁

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

守候你守候我

您实际上从未向test数组添加任何值。这行代码:double[] test = new double[numberArray.Length];只是说创建一个x大小的空白数组。该数组内的值是默认值(默认double值为0)。如果您希望它们在那里,您需要为数组分配值。将文本文件行转换为双数组的最简单方法是使用一点 Linq:if(File.Exists(newPath)){&nbsp; &nbsp; double[] test = File.ReadLines(newPath).Select(x => double.Parse(x)).ToArray()&nbsp; &nbsp; foreach(double number in test)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(number);&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; Console.ReadLine();}但是它的缺点是没有错误处理。如果你想处理错误,你的代码会稍微长一点,你应该创建一个ParseLines()方法:double[] test = ParseLines(newPath).ToArray()foreach(double number in test){&nbsp; &nbsp; Console.WriteLine(number);}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.ReadLine();private static IEnumerable<double> ParseLines(string filePath){&nbsp;&nbsp;&nbsp; &nbsp; if(File.Exists(newPath))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; foreach(string line in File.ReadLines(newPath))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; double output;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(double.TryParse(line, out output))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return output;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP