如何将小数存储在集合C#中?

我正在尝试编写一个程序,可以捕获用户输入的字符串类型。每当此字符串中有空格时,程序都需要获取字符串的该部分,然后尝试将其解析为十进制。这些条目可能是用逗号分隔的数字,而不仅仅是纯整数,这就是为什么我将使用小数而不是整数。

这是我到目前为止尝试过的:

static void Main(string[] args)
{
    Console.WriteLine("C# Exercise!" + Environment.NewLine);
    Console.WriteLine("Please enter two numbers seperated by space to start calculating: ");
    string[] input = Console.ReadLine().Split(' ');
    //Currently allows for more than one value... I am not necessarily looking for a solution to this problem however.
    Console.WriteLine(Environment.NewLine + "Result: ");
    //Create the collection of decimals:
    decimal[] numbers = { };
    numbers[0] = 1.0m;//<-- Results in a System.IndexOutOfRangeException
    for (int i = 0; i < input.Length; i++)
    {
        Console.WriteLine(input[i]);//<-- This value needs to be converted to a decimal and be added to a collection of decimals
    }
    /*decimal numberOne = ?? //<-- First decimal in the collection of decimals
    decimal numberTwo = ?? //<-- Second decimal in the collection of decimals
    Console.WriteLine(SumTrippler.Calculate(numberOne,numberTwo));*/
    Console.WriteLine(SumTrippler.Calculate(decimal.Parse("0.5"),(decimal)0.5));//<-- Irrelevant method
    Console.ReadKey();
}

如何从用户那里获得两个小数作为用户输入,并通过将其传递到程序底部的方法来处理该数据?

编辑:关闭此问题是因为您试图关联将字符串添加到列表的问题,但这并不是一个可靠的理由。我不是要在列表中添加字符串。

jing35711 回答:如何将小数存储在集合C#中?

您可以使用Array.ConvertAll()将字符串转换为十进制

var numbers = Array.ConvertAll(Console.ReadLine().Split(' '),decimal.Parse);
//Now you can iterate through decimal array
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

您的代码将如下所示,

using System;
using System.Linq;

public static void Main(string[] args)
{
    Console.WriteLine("C# Exercise!");
    Console.WriteLine("Please enter two numbers seperated by space to start calculating: ");
    var numbers = Array.ConvertAll(Console.ReadLine().Split(' '),decimal.Parse);

    Console.WriteLine("Result: ");
    for (int i = 0; i < numbers.Length; i++)
    {
        Console.WriteLine(numbers[i]);
    }
    decimal numberOne = numbers.FirstOrDefault(); 
    decimal numberTwo = numbers.LastOrDefault(); //Your second element will be last element in array
    Console.WriteLine(SumTrippler.Calculate(numberOne,numberTwo));
    Console.ReadKey();
}
,

您必须使用所需的字段数初始化数组(此后不能更改)

decimal[] numbers = new decimal[input.Length];
numbers[0] = 1.0m; // no more System.IndexOutOfRangeException
本文链接:https://www.f2er.com/3165972.html

大家都在问