简体   繁体   English

无法在C#的控制台中打印数组

[英]Not printing array in console in C#

I am trying to write a simple programm that displays multiples from 5 up to 1000. But the console is empty when executed. 我试图编写一个显示从5到1000的倍数的简单程序。但是执行时,控制台为空。 It is not clear to me why this is happening. 我不清楚为什么会这样。 I am still a beginner so please excuse this maybe stupid question. 我还是一个初学者,所以请原谅这个愚蠢的问题。 Thank you! 谢谢!

int[] nums = new int[] { };

for (int i=1; i < nums.Length; i++)
{
    //Checks if number is divisible by 5
    if (i%5 == 0)
    {
        //Creates Array input in right index
        int tst = i / 5 - 1;

        //Writes i to array
        nums[tst] = i;
    }
}

Console.WriteLine(String.Join("; ", nums));

Lenght of your nums array is zero. 您的nums数组的长度为零。 Your getting error for this. 您为此得到的错误。 For your example you have to create array which is min 200 lenght like that; 对于您的示例,您必须创建最小长度为200的数组;

int[] nums = new int[200]; // index will be 0 to 199

Arrays have a fixed length once they've been initialised and in this case the array you're creating has zero length (eg empty). 数组一旦初始化就具有固定的长度,在这种情况下,您要创建的数组的长度为零(例如,空)。

If you need to add to it dynamically, you're better off creating a List , and then when you need to use it, cast it into an array, like this: 如果需要动态添加它,最好创建一个List ,然后在需要使用它时,将其转换为数组,如下所示:

List<int> nums = new List<int>();
int countTarget = 1000;

for (int i = 1; i < countTarget; i++)
{
    //Checks if number is divisible by 5
    if (i % 5 == 0)
    {
        //Writes i to list
        nums.Add(i);
    }
}

Console.WriteLine(String.Join("; ", nums.ToArray()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM