取出用户输入整数中的每个数字,并显示每个数字到其十六进制值的转换?

时间:2018-10-23 17:54:01

标签: c++ visual-studio function hex decimal

我正在做一个程序,让用户输入一个十进制值,并且用户可以选择将其转换为二进制,八进制或十六进制。我将二进制和八进制转换降低了,但是我想进行十六进制转换。我知道,在C ++中,我要做的就是:

int convert = 78
cout << hex << convert << endl;

Output:
4e

但是那不是我要处理的。我想显示它,以便程序将整数中的每个数字取出,并显示该数字转换为十六进制。例如,我将向您展示如何进行二进制转换。

//Variable declaration
int b;
int d;
char decision;

//Declare function prototype
int convertDecimalToBinary(int);

//Welcome the user. Then ask them to enter a decimal value. The input will   be held in int d.
cout << "Welcome to The Converter!"; 

decimal:
cout << "\n" << "Please enter a decimal value: ";
cin >> d;

conversion:
//Ask the user if they want to conver this to Binary, Octal, or Hexadecimal
cout << "\n\nDo you want to convert " << d
    << " to Binary (b), Octal (o), or Hexadecimal (h)?: ;
cin >> decision;

//If the user wanted to do a binary conversion to the inputted decimal value
if (decision == 'b')
{
    //Call the convertDecimalToBinary function, and set the value of it equal to b.
    b = convertDecimalToBinary(d);

    //Output the conversion
    cout << "\n\nThe decimal value you inputted, " << d << ", in binary: " << b << endl;
}

 /*
    The convertDecimalToBinary function, this will take the user input (a decimal value) and convert it to binary.
    @param decimal, the decimal value the user inputted
    @return binary, the converted binary value.
*/
int convertDecimalToBinary(int decimal)
{
    //Declare variables for the function
    int x = decimal;
    int i = 0;
    int a = 1;
    int remainder;
    int binary = 0;
    int step;

    //Do the binary conversion until x=0
    while (x != 0)
    {   
        //Do the what was just explained. Set int step equal to x/2, set int remainder to x%2. Include counter addition, i++.
        i++;
        step = x / 2;
        remainder = x % 2;
        cout << "| Stage " << i << ": " << x << " / 2 = " << step << " | Remainder: " << remainder << " | " << endl;

        //This is to prevent and infinite loop
        x /= 2;

        //This will print out the remainder digits and form it in decimal
        //We need to do last remainder first, to first remainder last.
        binary += remainder * a;
        a *= 10;
    }

    //Return the conversion
    return binary;
}

这是输出的屏幕截图:

Output:

Please enter a decimal value: 109


Do you want to convert 109 to Binary (b), Octal (o), or Hexadecimal (h)?: b

| Stage 1: 109 / 2 = 54 | Remainder: 1 |
| Stage 2: 54 / 2 = 27 | Remainder: 0 |
| Stage 3: 27 / 2 = 13 | Remainder: 1 |
| Stage 4: 13 / 2 = 6 | Remainder: 1 |
| Stage 5: 6 / 2 = 3 | Remainder: 0 |
| Stage 6: 3 / 2 = 1 | Remainder: 1 |
| Stage 7: 1 / 2 = 0 | Remainder: 1 |


The decimal value you inputted, 109, in binary: 1101101

Octal实际上与此非常相似。但是您会看到逐步的方式。我希望能够提取一个数字,并将该数字转换为十六进制。显示该数字及其十六进制值,然后转到下一个数字。转换完所有数字后,返回主菜单并显示十六进制!那有可能吗,如果可以的话,我该如何做(如果可以的话,至少可以帮助我启动它)。谢谢大家!

0 个答案:

没有答案