简体   繁体   English

C#字符串数组加倍

[英]C# String Array to Double

Looking for some assistance. 寻找帮助。 I'm sure its really easy, but I just cannot seem to get my head around it. 我敢肯定它确实很简单,但是我似乎无法绕开它。

First, here's my code so far: 首先,这是到目前为止的代码:

        //Prompts user to enter numbers
    Console.Write("Enter a line of comma-seperated temperatures: ");
    string temps = Console.ReadLine();
    //Splits commas, seperating numbers into array
    string[] numsInString = temps.Split(',');
    int temps1 = numsInString.Length;
    int[] temps2 = new int[temps1];
    for (int i = 0; i < numsInString.Length; i++)
    {
        temps2[i] = int.Parse(numsInString[i]);
    }


    Console.WriteLine("Minimum temp: " + temps2.Min());
    Console.WriteLine("Average temp: " + temps2.Average());

So, it prompts the user to enter a temperature ie "5" separated by commas, "5,6,7,8". 因此,它提示用户输入温度,即以逗号分隔的“ 5”,“ 5、6、7、8”。 My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". 我的麻烦是我不能将温度设置在“ 5.4、5.7、6.3、6.8”之类的小数范围内。 I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that. 我发现我需要将字符串转换为双精度,但是我不确定如何做到这一点。

Thanks 谢谢

You want to change the type of your array to double[] and then change your parsing to parse double instead of int : 您想要将数组的类型更改为double[] ,然后将分析更改为分析double而不是int

double[] temps2 = new double[temps1];

for (int i = 0; i < numsInString.Length; i++)
{
    temps2[i] = double.Parse(numsInString[i]);
}

As a bit of an aside, you can also use LINQ to express this more declaratively: 顺便说一句,您还可以使用LINQ来更声明性地表达这一点:

double[] temps2 = temps.Split(',')
    .Select(double.Parse)
    .ToArray();

As already mentioned in other answers and comments you need change int[] array to double[] array and use double.Parse method for parsing strings to double. 正如其他答案和注释中已经提到的那样,您需要将int[]数组更改为double[]数组,并使用double.Parse方法将字符串解析为double。

But instead of loop or LINQ, I want suggest Array.ConvertAll method which will convert array of string to array of doubles. 但是我想建议使用Array.ConvertAll方法而不是循环或LINQ,它将字符串数组转换为双精度数组。

Console.Write("Enter a line of comma-seperated temperatures: ");
var rawData = Console.ReadLine();
var rawTemperatures = rawData.Split(',');  
var temperatures = Array.ConvertAll<string, double>(rawTemperatures, double.Parse);

Array.ConvertAll method will execute same for loop, but will be tiny tiny (in your case) more effective and enough declarative then LINQ approach Array.ConvertAll方法将对for循环执行相同的方法,但比LINQ方法更小巧(在您的情况下)更有效且声明性更强

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM