【发布时间】:2017-08-12 21:54:35
【问题描述】:
所以我刚刚想到将任何基数转换为十进制(以 10 为基数):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoloLearn
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is the number you want to convert?");
string num = Console.ReadLine();
Console.WriteLine("In what base is this number?");
int mathBase = int.Parse(Console.ReadLine());
double output = 0;
int j = 0;
char[] nums = num.ToCharArray();
for(int i=num.Length - 1; i>=0; i--) {
output = output + Math.Pow(mathBase,i) * nums[j] * 1;
Console.WriteLine("i: " + i +", j:" + j + ", nums[j]: " + nums[j] + ", output: " + output + ", mathBase: " + mathBase + ", " + Math.Pow(mathBase,i) + ".");
j++;
}
Console.WriteLine("The number " + num + " in base 10 (Decimal) is " + output + ".");
Console.ReadLine();
}
}
}
所以我从二进制 (num = 100, mathBase = 2) 开始,但答案变得疯狂。这就是为什么我添加了这段代码来看看到底发生了什么:
Console.WriteLine("i: " + i +", j:" + j + ", nums[j]: " + nums[j] + ", output: " + output + ", mathBase: " + mathBase + ", " + Math.Pow(mathBase,i) + ".");
j++;
好吧,所有变量都是正确的:
所以是的,我真的不知道会发生什么,因为所有的计算似乎都是正确的(Math.Pow(mathBase,i) = 2^2 = 4,如图所示,但是,4 * nums[j] = 4 * 1 = 196?如果有人知道到底发生了什么,请告诉我!
【问题讨论】:
标签: c# binary type-conversion decimal base