最终出局的额外零点来自哪里?

时间:2015-10-05 15:46:24

标签: c# loops logic

我编写了这段代码来命令从最大到最小的任何数字集,但无论出于何种原因,输出总是最后为零。我的问题是,它来自哪里? (新编码)

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();

1 个答案:

答案 0 :(得分:4)

您是否尝试处理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;
}