如何修复c#中“十进制到二进制”的代码

问题描述 投票:0回答:1

我在c#中从二进制公式输出公式时遇到问题

 static void Main(string[] args)
        {
            Console.Write("Input number : ");
            int num = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("The Formula : ");

            int accommodate = 0;

            for (int i = num; i > 0; i /= 2)
            {
                if (num % i == 0)
                {
                    accommodate++;

                    if (accommodate == 2)
                    {
                        Console.WriteLine(i + "/2 = 0");
                    }
                    else
                    {
                        Console.WriteLine(i + "/2 = 1" );
                    }

                }
            }
             Console.ReadKey();
        }

输出是

输入数量:12

公式 :

12/2 = 1“(X)这是错的,它应该是0”

6/2 = 0

3/2 = 1

1/2 = 1

c# algorithm binary decimal formula
1个回答
0
投票

将您的代码更改为此

accommodate % 2而不是accommodate % i

accommodate = i /= 2设置为for循环而不是accommodate++

Console.Write("Input number : ");
            int num = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("The Formula : ");

            int accommodate = 0;

            for (int i = num; i > 0; accommodate = i /= 2)
            {
                if (accommodate % 2 == 0)
                {

                    Console.WriteLine(i + "/2 = 0");
                }
                else
                {
                    Console.WriteLine(i + "/2 = 1");
                }
            }
            Console.ReadKey();
© www.soinside.com 2019 - 2024. All rights reserved.