我正在尝试编写一个程序,该程序可以捕获字符串类型的用户输入。每当这个字符串中有一个空格时,程序就需要获取字符串的这一部分,并尝试将其解析为十进制。条目可能是用逗号分隔的数字,而不仅仅是普通整数,这就是为什么我会使用小数而不是整数。
这就是我迄今为止所尝试的:
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();
}
我如何从用户那里获得两个小数作为用户输入,并通过将其传递到程序底部的方法来处理这些数据?
编辑:因为你试图将一个添加字符串到列表中的问题关联起来,所以关闭这个问题并不是一个可靠的原因。我不想在列表中添加字符串。
您可以使用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