【发布时间】:2015-09-21 14:33:21
【问题描述】:
所以我们被要求将十六进制值(存储在字符串中)转换为其十进制值。字符串中的每个字符都应在循环内手动转换为十进制,然后发布十六进制值的总十进制值。我得到了我编写的代码,但我无法确定我可能在哪里出错,因为“F4”Hexa(例如)具有“292”而不是“244”的十进制等效值。我已经调试了所有东西,代码看起来很好。有什么想法吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdvProgCS
{
class Program
{
static int dec=0;
static string hex;
static void Main(string[] args)
{
do{
Console.Write("[Press 0 to Stop] Hexadecimal Value: ");
hex = Console.ReadLine();
if (hex == "0") break;
int length = hex.Length;
for (int i = 0; i < length+1; i++)
{
if (hex[i] == 'A' || hex[i] == 'B' || hex[i] == 'C' || hex[i] == 'D' || hex[i] == 'E' || hex[i] == 'F')
{
if (hex[i] == 'A')
dec+= 10 * Convert.ToInt32(Math.Pow(16, length - 1));
if (hex[i] == 'B')
dec += 11 * Convert.ToInt32(Math.Pow(16, length - 1));
if (hex[i] == 'C')
dec += 12 * Convert.ToInt32(Math.Pow(16, length - 1));
if (hex[i] == 'D')
dec += 13 * Convert.ToInt32(Math.Pow(16, length - 1));
if (hex[i] == 'E')
dec += 14 * Convert.ToInt32(Math.Pow(16, length - 1));
if (hex[i] == 'F')
dec += 15 * (Convert.ToInt32(Math.Pow(16, length - 1)));
}
else
dec += hex[i];
length--;
}
Console.WriteLine("DECIMAL EQUIVALENT: " + dec + "\n");
}
while(hex != "0");
}
}
}
【问题讨论】:
-
为什么是复杂的解析?见stackoverflow.com/questions/1139957/…
-
哦,我明白了...家庭作业...
标签: c# command-line hex decimal