mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-04 11:09:52 +08:00
Reduced Lines of code
Using a "HexValues" string to store the possible hex values(0-9 A-F). Changed "void main" to "int main"
This commit is contained in:
@@ -2,50 +2,25 @@
|
||||
|
||||
using namespace std;
|
||||
|
||||
void main(void)
|
||||
{
|
||||
int main(void){
|
||||
int valueToConvert = 0; //Holds user input
|
||||
int hexArray[8]; //Contains hex values backwards
|
||||
int i = 0; //counter
|
||||
int lValue = 0; //Last Value of Hex result
|
||||
char HexValues[] = "0123456789ABCDEF";
|
||||
|
||||
cout << "Enter a Decimal Value" << endl; //Displays request to stdout
|
||||
cin >> valueToConvert; //Stores value into valueToConvert via user input
|
||||
|
||||
while (valueToConvert > 0) //Dec to Hex Algorithm
|
||||
{
|
||||
lValue = valueToConvert % 16; //Gets remainder
|
||||
valueToConvert = valueToConvert / 16;
|
||||
hexArray[i] = lValue; //Stores converted values into an array
|
||||
i++;
|
||||
while (valueToConvert > 15){ //Dec to Hex Algorithm
|
||||
hexArray[i++] = valueToConvert % 16; //Gets remainder
|
||||
valueToConvert /= 16;
|
||||
}
|
||||
hexArray[i] = valueToConvert; //Gets last value
|
||||
|
||||
cout << "Hex Value: ";
|
||||
while (i > 0)
|
||||
{
|
||||
//Displays Hex Letters to stdout
|
||||
switch (hexArray[i - 1]) {
|
||||
case 10:
|
||||
cout << "A";
|
||||
break;
|
||||
case 11:
|
||||
cout << "B";
|
||||
break;
|
||||
case 12:
|
||||
cout << "C";
|
||||
break;
|
||||
case 13:
|
||||
cout << "D";
|
||||
break;
|
||||
case 14:
|
||||
cout << "E";
|
||||
break;
|
||||
case 15:
|
||||
cout << "F";
|
||||
break;
|
||||
default:
|
||||
cout << hexArray[i - 1]; //if not an int 10 - 15, displays int value
|
||||
}
|
||||
i--;
|
||||
}
|
||||
while (i >= 0)
|
||||
cout<<HexValues[hexArray[i--]];
|
||||
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user