我是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();
}
}
}
答案 0 :(得分:0)
小黑客:
if (remainder < 10) output = Convert.ToString(remainder) + output;
else if (remainder <= 16)
{
int result = 'A' + (remainder - 10);
output = (char)result + output;
}
无论如何 - 如果你想将dec转换成十六进制,你的代码就错了。十六进制中没有G
。
因此,remainder == 16
的情况永远不会发生 - remainder % 16
的输出属于集[0...15]
。
所以你也可以放else if (remainder <= 15)
。
答案 1 :(得分:0)
似乎最后的if else条件是重复的,你想要摆脱它。所以情况是answer
变为零,我们仍然想再次运行循环。处理这个问题可能有很多选择,但我想告诉你三个
这可能会解决你在循环后重复代码的if else条件。试一试。
int answer = input / 16;
int remainder = input % 16;
bool shudloop = true;
int cntshudloop = 0;
while(shudloop)
{
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(answer == 0)
{
if(cntshudloop >= 1)
shudloop = false;
cntshudloop++;
}
}