为什么c#编译器在任何数字之前都没有读取0?

avi*_*irk 0 c# types

int n;
        int[] ar = new int[50];
        Console.Write("Enter the size of array= ");
        n = int.Parse(Console.ReadLine());
        for (int i = 0; i < n; i++)
        {
            ar[i] = int.Parse(Console.ReadLine());
        }
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine("AR["+i+"]="+ar[i]);
        }
        Console.Read();
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在这里你可以看到,当进入09或08时,它将删除它并打印9和8.当在c ++编译器上运行时,它在不同的索引上打印0和9,为什么两种语言的编译器做这样的行为?为什么他们不读一位数?

Nat*_*han 10

int.Parse(..)和其他字符串到数值解析函数的行为是去掉任何与数值无关的前导字符(在这种情况下为零).

如果您希望保持前导零,则将数组的数据类型更改为字符串.

既然你已经发布了一些代码,这里有一些建议(评论内联)

    int n;
    bool validNumber;
    do {
      validNumber = true;
      Console.Write("Enter the size of array:");
      if(!int.TryParse(Console.ReadLine(), out n)) // use TryParse instead of Parse to avoid formatting exceptions
      {
          Console.WriteLine("Not a number, please try again");
          validNumber = false;
      }
    } while(!validNumber);  // re-prompt if an invalid number has been entered

    int[] ar = new int[n];    // declare the array after the size is entered - your code will break if the user enters a number greater than 50

    // change to "string[] ar = new string[n];" if you want to keep the full value entered

    for (int i = 0; i < n; i++)
    {
        bool valid;
        do {
          valid = true;
          int num;
          string value = Console.ReadLine();
          if(int.TryParse(value, out num))  // again - use tryparse.
            ar[i] = num;  // change to "ar[i] = value;" if you're using a string array. 
          else {
            Console.WriteLine("Please enter that again - not a number");
            valid = false;
          }
       } while(!valid);

    }
    for (int i = 0; i < n; i++)
    {
        Console.WriteLine("AR["+i+"]="+ar[i]);
    }
    Console.Read();
Run Code Online (Sandbox Code Playgroud)


Mic*_*ard 5

您的数组存储整数,并且由于01和1具有相同的数字值,因此我们不区分它们.

如果需要保留前缀零,则需要将它们保存为字符串.