简体   繁体   English

我的代码有什么问题(它处理数组大小)?

[英]What is wrong with my code (it deals with array size)?

I am initializing array size to 1 but I am updating it in the subsequent lines. 我正在将数组大小初始化为1,但在随后的几行中对其进行了更新。 It is not even storing the first element in the array as the array size is 1 initially but I expected it would. 它甚至没有在数组中存储第一个元素,因为最初数组的大小为1,但我希望这样。 Could someone provide me with an explanation? 有人可以给我一个解释吗? Here is the code: 这是代码:

  class Program
  {
    static void Main(string[] args)
    {
      int num = int.Parse(Console.ReadLine());
      Console.Write("The binary number for " + num + " is  ");
      int size = 1;
      int[] binary = new int[size];
      size = 0;
      while(num>=1)
      {
        if (num % 2 == 0)
          binary[size++] = 0;
        else
          binary[size++] = 1;
          //size += 1;
          num = num / 2;
      }

      for (int i = size - 1; i >= 0; i--)
      {
        Console.Write(binary[i]);
      }
      Console.WriteLine();
      Console.Write("The Compliment of this number is  ");
      for (int i = size - 1; i >= 0; i--)
      {
        if (binary[i] == 0)
          binary[i] = 1;
        else
          binary[i] = 0;
      }
      for (int i = size - 1; i >= 0; i--)
      {
          Console.Write(binary[i]);
      }
      Console.WriteLine();
      Console.ReadKey();
    }
  }

您无法调整数组的大小,数组的长度始终是初始化期间指定的长度(在您的情况下为1)。

I think the problem is specifically in your expectation that you can update an array size "in the subsequent lines." 我认为问题特别出在您期望您可以“在后续行中”更新数组大小。

When you make the array here: 当您在此处制作数组时:

int[] binary = new int[size]; int [] binary = new int [size];

Then the size is set in stone 然后将尺寸固定在石头上

When you call something like: binary[size++] = 0; 当您调用类似的东西时:binary [size ++] = 0; This will not actually increase the number of slots in your array. 这实际上不会增加​​阵列中的插槽数量。 In fact, that code is only changing the index where you are looking to read or write values. 实际上,该代码只会更改您要读取或写入值的索引。 I can see that your code is going to quickly go out of bounds of the array (if you ask for anything but binary[0] 我可以看到您的代码将很快超出数组的范围(如果您要求的不是binary [0],

It turns out this array is a tricky data type to use; 事实证明,此数组是要使用的棘手数据类型。 arrays have a fixed size on creation. 数组在创建时具有固定的大小。 You want something that can grow! 您想要可以成长的东西! So you can either: 因此,您可以:

-Use an array, but declare that it's size is Math.Ciel(logbase2(yourNumber)) to make sure you will have enough space -使用数组,但声明其大小为Math.Ciel(logbase2(yourNumber))以确保您有足够的空间

-Use a data structure that can grow, like a string or list -使用可以增长的数据结构,例如字符串或列表

-You can create a new array every time you need it bigger and assign it like: -您可以在每次需要更大的数组时创建一个新数组,并将其分配为:

binary = new int[++size];
binary[size-1]=whatever

Good luck, hope this helps! 祝你好运,希望这会有帮助!

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

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