将连续输入的数字分配给数组 3 6 23 12 4 a[0]=3 a[1]=6 a[2]=23 a[3]=12 a[4]=10
Posted
技术标签:
【中文标题】将连续输入的数字分配给数组 3 6 23 12 4 a[0]=3 a[1]=6 a[2]=23 a[3]=12 a[4]=10【英文标题】:assigning numbers entered in a row to an array 3 6 23 12 4 a[0]=3 a[1]=6 a[2]=23 a[3]=12 a[4]=10 【发布时间】:2021-12-22 06:01:13 【问题描述】: string[] n = Console.ReadLine().Split();
for (int i = 1; i <6; i++)
int[] a = long.Parse(n[i]);
【问题讨论】:
【参考方案1】:如果一行中的每个数字都用空格分隔 - 您可以更有效地使用 Split
:
int[] array = Console.ReadLine().Split().Select(int.Parse).ToArray(); // Improved according to @Caius Jard comment
如果需要 long
s 的数组 - 将 int.Parse
替换为 long.Parse
并将变量声明为 long[] array
。
您需要添加using System.Linq
才能访问ToArray
扩展方法。
编辑。
灵感来自 @Caius Jard,非 LINQ 版本:
// Read input line and split it by whitespace (default)
string[] values = Console.ReadLine().Split();
// Declare arrays for Int or Long values.
// Arrays sizes equals to size of array of input values
int[] arrayOfInts = new int[values.Length];
long[] arrayOfLongs = new long[values.Length];
// Iterate with for loop over amount of input values.
for (int i = 0; i < values.Length; i++)
// Convert trimmed input value to Int32
arrayOfInts[i] = int.Parse(values[i].Trim());
// Or to Int64
arrayOfLongs[i] = long.Parse(values[i].Trim());
int.Parse
和 long.Parse
可以根据需要替换为 Convert.ToInt32
和 Convert.ToInt64
。
【讨论】:
Split().Select(int.Parse)
会很好,尽管整体 LINQ 可能不适用于作为家庭作业的 Programming 101【参考方案2】:
请不要使用魔法常量:i < 6
。这里6
不一定等于n.Length
。
你可以把它写成
string[] n = Console.ReadLine().Split();
List<int> list = new List<int>();
for (int i = 0; i < n.Length; ++i)
if (int.TryParse(n[i], out int value))
list.Add(value);
else
// Invalid item within user input, say "bla-bla-bla"
//TODO: either reject the input or ignore the item (here we ignore)
if (list.Count == a.Length)
// We have exactly a.Length - 6 valid integer items
for (int i = 0; i < a.Length; ++i)
a[i] = list[i];
else
//TODO: erroneous input: we have too few or too many items
【讨论】:
谢谢兄弟你有电报或脸书以上是关于将连续输入的数字分配给数组 3 6 23 12 4 a[0]=3 a[1]=6 a[2]=23 a[3]=12 a[4]=10的主要内容,如果未能解决你的问题,请参考以下文章