I am a few days new to the C# language and wanted to challenge myself by writing a program to convert a normal integer to hexadecimal. I think this program works properly but I want to get rid of the second set of if/else statements, is it possible to rewrite the code in the while loop for that to happen?
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;
else if (remainder == 16) output = "G" + 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;
else if (remainder == 16) output = "G" + output;
Console.WriteLine("Your number in hexadecimal is: 0x" + output);
Console.ReadLine();
}
}
}
Aucun commentaire:
Enregistrer un commentaire