【发布时间】:2013-10-17 20:18:16
【问题描述】:
我目前在尝试让我的程序将二进制数转换为正确的十进制等值时遇到了很大的困难。有了我所拥有的,它给了我正确的数量,比如 111=7,但它给了我错误的数量,比如 1101 = 11,而它应该是 13。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num;
//int n;
Console.WriteLine("Enter a number");
num = Convert.ToInt16(Console.ReadLine());
//n = num;
bintonum(num);
}
public static void bintonum (int num)
{
int dig;
double sum = 0;
while (num > 0)
{
dig = num % 10; //takes the number and breaks it down into each digit
sum = dig + (sum * 2); //reverses the number and adds the digit aquired from the previous line
num = num / 10; // reduces the number by one digit to get to zero
}
Console.WriteLine("{0}", sum);
}
}
}
【问题讨论】:
-
这是一个不允许你使用内置功能的学校项目吗?
-
需要自己写转换算法吗?正如@zimdanen 在下面回答的那样,此功能内置于 .NET 框架中。
-
如果您可以使用 zimdanen 的答案,那就太好了!如果您需要公式,请尝试查看this SO question and answers
-
你的代码倒转,1011 = 11。
-
好的,所以很接近,当时只是倒退了
标签: c# binary decimal console-application