读取由空间隔开的N长度阵列

发布于 2025-01-27 06:44:30 字数 315 浏览 3 评论 0原文

您知道从控制台中获取用户输入的更好方法吗?输入的第一行由单个数字N组成,即我们的数组的长度。二线的n个数字被空间隔开。 我的代码看起来像这样:

int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
string[] stringarray;
stringarray = Console.ReadLine()).Split(' ');
for (int i = 0; i < n; i++)
{
    arr[i] = Convert.ToInt32(stringarray[i]);
}

Do you know a better way to take user input from the console? The first line of input consists of a single number n, which is the length of our array. Second-line has n numbers separated by spaces.
My code looks like this:

int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
string[] stringarray;
stringarray = Console.ReadLine()).Split(' ');
for (int i = 0; i < n; i++)
{
    arr[i] = Convert.ToInt32(stringarray[i]);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

左耳近心 2025-02-03 06:44:30

您可以使用LINQ而不是像以下线这样的循环:

arr = Console.ReadLine().Split(' ').Select(e => Convert.ToInt32(e)).ToArray();

最终代码:

int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
arr = Console.ReadLine().Split(' ').Select(e => Convert.ToInt32(e)).ToArray();

You can use Linq instead of loop like this line:

arr = Console.ReadLine().Split(' ').Select(e => Convert.ToInt32(e)).ToArray();

Final Code:

int n = int.Parse(Console.ReadLine());
int[] arr = new int[n];
arr = Console.ReadLine().Split(' ').Select(e => Convert.ToInt32(e)).ToArray();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文