如何在 C# 中将拆分字符串(字符串数组)转换为双精度

本文关键字:字符串 数组 转换 双精度 拆分 | 更新日期: 2023-09-27 18:36:04

问题:

8名儿童的身高正在检查和插入。
在控制台中插入 8 个双精度值,并制定算法以找出最低高度和最大高度。

这就是我所做的:

class work1 {
    public static void Main(String[] args) {
        string[] height = Console.ReadLine().Split(' ');
        double[] heightInDouble = new Double[height.Length];
        for (int i = 0; i <= height.Length; i++) {
            heightInDouble[i] = (double) height[i]; // line 20
        }
        Console.WriteLine("Highest: " + heightInDouble.Max() + " Lowest: " + heightInDouble.Min());
    }
}

结果:

错误:无法将类型"字符串"转换为"双精度"(20)

如何将字符串转换为双精度值

如何在 C# 中将拆分字符串(字符串数组)转换为双精度

不能直接从字符串转换为双精度。 使用double.Parse

realInts[i] = double.Parse( ints[i] );

您可能还想使用 TryParse ,因为这里不确定字符串实际上是一个数字:

double parsedValue;
realInts[i] = double.TryParse(ints[i], out parsedValue) ? parsedValue : 0;

还有一点说明:您可以使用 Linq 表达式链来简化语法:

double parsedVal;
double[] realInts = Console.ReadLine().Split(' ')
    .Select(str => double.TryParse(str, out parsedVal) ? parsedVal : 0)
    .ToArray();

试试这个。

static void Main(string[] args)
    {
        string[] ints = Console.ReadLine().Split(' ');
        double[] realInts = new Double[ints.Length];
        for (int i = 0; i <= ints.Length; i++)
        {
            double val;
            if (Double.TryParse(ints[i], out val))
            {
                realInts[i] = val; // line 20
            }
            else
            {
                // Unable to parse
                realInts[i] = 0;
            }
        }
    }

使用此代码

class work1
{
    public static void Main(String[] args)
    {
        string[] height = Console.ReadLine().Split(' ');
        double[] heightInDouble = new Double[height.Length];
        for (int i = 0; i < height.Length; i++)
        {
            heightInDouble[i] = Convert.ToDouble(height[i]); // line 20
        }
        Console.WriteLine("Highest: " + heightInDouble.Max() + " Lowest: " + heightInDouble.Min());
        Console.ReadLine();
    }
}