我在使用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
答案 0 :(得分:0)
将代码更改为此
accommodate % 2
代替accommodate % i
在for循环中设置accommodate = i /= 2
而不是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();