2016-11-03 97 views
0

我的任务是使用将十六进制整数转换为十进制形式的循环编写程序。请勿使用内置的.NET功能。通过在C#中将十六进制转换为十进制数而溢出

我编写了程序,它适用于除“4ED528CBB4”之外的所有测试,并在“D”后溢出。我用很久的结果,我找不到问题。

 string hexadecimal = Console.ReadLine(); 
     long result = 0; 

      for (int i = 0; i < hexadecimal.Length; i++) 
      { 

       if (hexadecimal[hexadecimal.Length - i - 1] >= '0' && hexadecimal[hexadecimal.Length - i - 1] <= '9') 
       { 
        result += ((hexadecimal[hexadecimal.Length - i - 1] - '0') * (int)Math.Pow(16, i)); 
       } 
       else if (hexadecimal[hexadecimal.Length - i - 1] == 'D') 
       { 
        result += (13 * (int)Math.Pow(16, i)); 
       } 
       else if (hexadecimal[hexadecimal.Length - i - 1] == 'C') 
       { 
        result += (12 * (int)Math.Pow(16, i)); 
       } 
       else if (hexadecimal[hexadecimal.Length - i - 1] == 'A') 
       { 
        result += (10 * (int)Math.Pow(16, i)); 
       } 
       else if (hexadecimal[hexadecimal.Length - i - 1] == 'B') 
       { 
        result += (11 * (int)Math.Pow(16, i)); 
       } 
       else if (hexadecimal[hexadecimal.Length - i - 1] == 'F') 
       { 
        result += (15 * (int)Math.Pow(16, i)); 
       } 
       else if (hexadecimal[hexadecimal.Length - i - 1] == 'E') 
       { 
        result += (14 * (int)Math.Pow(16, i)); 
       } 

      } 
      Console.WriteLine(result); 
     } 

    } 
+0

尝试无符号整数 – jdweng

+0

将所有的转换从'(int)'改为'(long)',它适用于我。你也可以在溢出时抛出异常的操作加上'checked()'(如果溢出足够了,它会再次变为正值,你甚至可能不会注意到溢出):'result + = checked((13 * (long)Math.Pow(16,i)));'。我只是简单地看了一下,但它看起来像'13 *(int)Math.Pow()'是在转换为'int'的地方溢出了,但是乘以13被推到'int'的极限。 – Quantic

+0

坦克的答案。我添加了'checked'并将所有内容都改为'long',现在出现了溢出消息。如何解决这个问题? – Mina

回答

0

如果您reult参数long,你不应该做的是类型转换?