【问题标题】:How do I Convert a txt file to an array of floats (in c#)?如何将 txt 文件转换为浮点数组(在 c# 中)?
【发布时间】:2019-09-09 15:08:08
【问题描述】:

我已将一个文件读入我的 c# 项目中的一个变量中,并希望将其转换为一个浮点数组。

这是 txt 文件的示例:

-5.673

10.543

-0.322

10.048

文件包含一个数字,后跟一个空行和另一个数字。

我使用以下代码将文件读入我的项目:

var numbers = File.ReadAllLines(@"numbers.txt")

如何将numbers 转换为浮点数组?

谢谢

【问题讨论】:

    标签: c# arrays type-conversion


    【解决方案1】:

    您可以使用Linqfloat.Parse()

    var floats = numbers.Where(s => s != String.Empty).Select(s => float.Parse(s, CultureInfo.InvariantCulture)).ToArray();
    

    但如果文件中的数据不正确,则会出现异常。要检查值是否正确float,请使用float.TryParse()

    【讨论】:

      【解决方案2】:

      变量var 的类型是String[],所以在这种情况下,您可以从数组的偶数位置获取值,然后转换为float

      【讨论】:

        【解决方案3】:

        你的程序应该遍历文件中当前存储在numbers变量中的每一行,该变量的类型为String[],检查该行的值是否为空,如果不是,将其转换为浮动并将其添加到我们的浮动数组中。

        把这一切放在一起看起来像这样:

        string[] numbers = File.ReadAllLines(@"numbers.txt");
        
        // Create a list we can add the numbers we're parsing to. 
        List<float> parsedNumbers = new List<float>() ;
        
        for (int i = 0; i < numbers.Length; i++) 
        {
            // Check if the current number is an empty line
            if (numbers[i].IsNullOrEmpty()) 
            {
                continue;
            }
            // If not, try to convert the value to a float
            if (float.TryParse(numbers[i], out float parsedValue))
            {
                // If the conversion was successful, add it to the parsed float list 
                parsedNumbers.Add(parsedValue);
            }
        } 
        
        // Convert the list to an array
        float[] floatArray = new float[parsedNumbers.Length];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-02
          • 2017-09-12
          • 1970-01-01
          相关资源
          最近更新 更多