如何声明每次操作完成时增加的变量?

时间:2017-12-13 21:02:19

标签: c# arrays binary increment reverse

我是一个非常初学者,刚开始学习c#。我想创建一个简单的控制台应用程序,将数字从十进制转换为二进制。

我做到了:

static void Main(string[] args)
{
    Console.Write("Which decimal number do you want to convert into binary :  ");
    long nr_dec = long.Parse(Console.ReadLine());

    int p = 0;
    long[] nrbin = new long[p];
    int i = 0;

    while (nr_dec > 1)
    {
        nrbin[i] = nr_dec % 2;
        i++;
        nr_dec /= 2;
        p++;
    }
    nrbin[i] = 1;

    for (i = 0; i < nrbin.Length; i++)
    {
        Console.Write(nrbin[i]);
    }

    Console.ReadKey();
}

这是中途工作。我不知道我需要在阵列中存储多少个地方(例如,二进制中的5个是101并且我想存储3个位置),这样我希望每次从%获得数字时P都会增加然后数组应该有p个元素,但我不知道该怎么做(因为我在数组声明之后增加p并且p在开头是0所以它存储了0个位置)而且我也不知道如何使数组显示从最后到第一个的元素。 //我尝试了一个列表,但现在我得到了 指数超出范围。必须是非负数且小于集合的大小。参数名称:index

static void Main(string[] args)
            {

        Console.Write("Which decimal number do you want to convert into binary :  " );
        long nr_dec = long.Parse(Console.ReadLine());


        List<long> nrbin=new List<long>() ;
        int i=0;


        while(nr_dec> 1)
        {
            nrbin[i] = nr_dec % 2;
            i++;
            nr_dec /= 2;

        }
        nrbin[i] = 1;



        for ( i =0;i<nrbin.Count;i++)
        {
            Console.Write(nrbin[i]);
        }




        Console.ReadKey();
    }
}

}

1 个答案:

答案 0 :(得分:0)

试试此代码

static void Main(string[] args)
    {
        Console.Write("Which decimal number do you want to convert into binary :  ");
        long nr_dec = long.Parse(Console.ReadLine());            

        var nrbin = new List<long>();           

        while (nr_dec > 1)
        {
            var bin = nr_dec % 2;
            nrbin.Add(bin);                
            nr_dec /= 2;               
        }           
        nrbin.Add(1);
        nrbin.Reverse();
        foreach (var num in nrbin)
        {
            Console.Write(num);
        }           

        Console.ReadKey();
    }

我没有改变代码的逻辑只是进行了一些更改,以便您现有的算法有效。我没有使用数组,而是使用了List,最后将其反转,以便显示正确的二进制文件。