【发布时间】:2017-03-31 14:19:18
【问题描述】:
我刚接触 C# 语言几天,想通过编写一个将普通整数转换为十六进制的程序来挑战自己。我认为这个程序可以正常运行,但我想摆脱第二组 if/else 语句,是否可以重写 while 循环中的代码以实现这一点?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IntegerToHexadecimal
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter an integer");
int input = Convert.ToInt32(Console.ReadLine());
string output = "";
int answer = input / 16;
int remainder = input % 16;
while (answer != 0)
{
if (remainder < 10) output = Convert.ToString(remainder) + output;
else if (remainder == 10) output = "A" + output;
else if (remainder == 11) output = "B" + output;
else if (remainder == 12) output = "C" + output;
else if (remainder == 13) output = "D" + output;
else if (remainder == 14) output = "E" + output;
else if (remainder == 15) output = "F" + output;
input = answer;
answer = input / 16;
remainder = input % 16;
}
if (remainder < 10) output = Convert.ToString(remainder) + output;
else if (remainder == 10) output = "A" + output;
else if (remainder == 11) output = "B" + output;
else if (remainder == 12) output = "C" + output;
else if (remainder == 13) output = "D" + output;
else if (remainder == 14) output = "E" + output;
else if (remainder == 15) output = "F" + output;
Console.WriteLine("Your number in hexadecimal is: 0x" + output);
Console.ReadLine();
}
}
}
【问题讨论】:
-
为什么不
ToString("X")这会告诉你 int 的十六进制 -
@MohitShrivastava 十六进制中没有“G”。
-
@pwas 你是绝对正确的。虽然我还没有看到它,但现在出现的问题是 OP 到处都在写 HEX。
Console.WriteLine("Your number in hexadecimal is: 0x" + output);和namespace IntegerToHexadecimal以及描述中 -
@MohitShrivastava 啊对,所以看来 OP 的代码工作不正常。
-
我的坏@pwas 新人没有意识到十六进制中没有 G
标签: c# if-statement while-loop