我在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
将您的代码更改为此
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();