在数组中的两个数字之间存储数字

MyA*_*xro 0 .net c# visual-studio

你可以从标题中读到我试图在数组中存储两个数字之间的所有数字.例如,将数字存储在数组中的21到43之间(22,23,24,25,26,27,28,29 ...).

这是代码,我不知道为什么,但它只打印较高的数字减1.

class Program
{

    static void Main(string[] args)
    {

        int higher = 43;
        int lower = 21;
        int[] numbers = new int[22]; //the numbers between 21 and 43 are 22

        for (int i = lower; i < higher;i++)
        {
            for (int a = 0; a < 22; a++)
            {
                numbers[a] = i;
            }
        }
        for (int c = 0; c < 22; c++)
        {
            Console.WriteLine(numbers[c]);
        }
        Console.ReadLine();

    }
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 10

这是代码,我不知道为什么,但它只打印较高的数字减1.

这个问题将吸引答案,为您提供六种解决方案,您可以剪切并粘贴以完成任务.

我注意到你没有在你的问题中提出问题 - 下次,请以问题的形式格式化你的问题.这里要问的正确问题是如何在我编写的代码中学习如何发现错误?因为那是你缺乏的重要技能.给你代码的答案不会回答这个问题.

我已经给你一个最近答案的链接,我在那里详细解释,所以研究一下.

特别是,在您的情况下,您必须阅读您编写的程序,就好像您没有编写它一样.好像你对其他人写的程序感到满意,并试图找出它的作用.

我要做的第一件事就是看内循环并对自己说"这样做,用语言做什么?"

        for (int a = 0; a < 22; a++)
        {
            numbers[a] = i;
        }
Run Code Online (Sandbox Code Playgroud)

那就是"将值i放在数组的每个槽中.现在看一下外部循环:

    for (int i = lower; i < higher;i++)
    {
        put the value i in every slot of the array
    }
Run Code Online (Sandbox Code Playgroud)

现在使用的技术是逻辑上"展开"循环.循环只是做了多次,所以写出来.它从较低的开始,它变为更高的1,所以循环执行此操作:

        put the value lower in every slot of the array
        put the value lower+1 in every slot of the array
        …
        put the value higher-1 in every slot of the array
Run Code Online (Sandbox Code Playgroud)

第三个循环做什么?

        print every item in the array
Run Code Online (Sandbox Code Playgroud)

现在你知道为什么它打印最多的数字减去一次多次.因为这就是程序的作用.我们只是推理出来了.


顺便说一句,到目前为止发布的答案是正确的,但有些并不是最好的.

您有一种技术可以理解为"对数组的每个成员执行某些操作,即:

loop an indexer from 0 to the array size minus one
    do something to the array slot at the indexer
Run Code Online (Sandbox Code Playgroud)

但其他答案提出的解决方案恰恰相反:

loop an indexer from the lower to the higher value
    compute an index
    do something to the array slot at that index
Run Code Online (Sandbox Code Playgroud)

重要的是要理解两者都是正确的,但我的感觉是,对于初学者,你应该坚持你所知道的模式.我们怎么样?

loop an indexer from 0 to the array size minus one
    do something to the array slot at the indexer
Run Code Online (Sandbox Code Playgroud)

为你的问题?让我们开始为您提供一个更好的循环索引器的技术:

for (int i = 0; i < numbers.Length; ++i)
Run Code Online (Sandbox Code Playgroud)

这是一种更好的技术,因为当你改变数组的大小时,你不必改变循环!此外,您还可以保证阵列中的每个插槽都被覆盖. 设计你的循环,使它们对变化具有鲁棒性并具有良好的不变量.

现在你必须弄清楚正确的循环体是什么:

{
    int number = i + lower;
    numbers[i] = number;
}
Run Code Online (Sandbox Code Playgroud)

现在你知道你的循环不变量是"当循环完成时,数组中充满了从较低位置开始的连续数字".