最后输出的额外零是怎么来的

本文关键字:输出 最后 | 更新日期: 2023-09-27 18:16:01

我编写这段代码是为了对任何一组数字进行从大到小的排序,但不知什么原因,输出总是在末尾有一个零。我的问题是,它从何而来?(编码新手)

Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
    Console.WriteLine("Please enter entry number " + counter);
    int number = Convert.ToInt16(Console.ReadLine());
    array[i] = number;
        counter++;
}
for (int x = 0; x <= input; x++)
{
    for (int i = 1; i <=input; i++)
    {
        if (array[i - 1] <= array[i])
        {
            temp1 = array[i - 1];
            temp2 = array[i];
            array[i - 1] = temp2;
            array[i] = temp1;
        }
    }
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
    Console.Write(array[i] + " ");
}
Console.ReadLine();

最后输出的额外零是怎么来的

您是否试图处理input + 1input元素之间不一致。例如:

int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
    Console.WriteLine("Please enter entry number " + counter);
    int number = Convert.ToInt16(Console.ReadLine());
    array[i] = number;
    counter++;
}

您正在创建一个包含input + 1个元素的数组,但只填充其中的input个元素。

一般来说,在循环中使用排他上边界要常见得多。例如:

int[] array = new int[input];
for (int i = 0; i < input; i++)
{
    // No need for the counter variable at all
    Console.WriteLine("Please enter entry number " + (i + 1));
    int number = Convert.ToInt16(Console.ReadLine());
    array[i] = number;
}