简体   繁体   English

十进制转十六进制 C++

[英]Decimal to Hex in C++

I've coded this program to get a number and a base as two inputs, then prints the number in the given base, it does work well when the base is less than 10, but when I enter a base like 16, instead of printing the word "A" for 10, or F for 15, the program prints the ASCII value of the words, but I want the words themselves.我已经编写了这个程序来获得一个数字和一个基数作为两个输入,然后在给定的基数中打印数字,当基数小于 10 时它工作得很好,但是当我输入像 16 这样的基数时,而不是打印单词“A”代表 10,或 F 代表 15,程序打印单词的 ASCII 值,但我想要单词本身。


#include <iostream>
using namespace std;

int base(int n, int t);

int main()
{
    char ch;
    do {
        int n=0, t=0;
        base(n,t);
        
        cout << "\n\nDo you want to continue?(y/n)";
        cin >> ch;
    } while (ch=='y');

}

int base(int n, int t)
{
    cout << "\nPlease enter the number : ";
    cin >> n;
    cout << "\nPlease enter the base : ";
    cin >> t;
    
    int i=80;
    int x[i];
    int m=n;
    

    for (i=1; n>=t ;i++) 
    {
        int rem;
        rem = n%t;
        n = n/t;


    if (rem>9)
    { 
        switch (char(rem)) 
        {
            case 10 :
                rem = 'A';
                break;
            case 11 :
                rem = 'B';
                break;
            case 12 :
                rem = 'C';
                break;
            case 13 :
                rem = 'D';
                break;
            case 14 :
                rem = 'E';
                break;
            case 15 :
                rem = 'F';
                break;
        }
    } 
    

    x[i]=rem;
    }
    

    cout << "The number " << m << " in base " << t << " is = ";
    cout << n;
            

    for (int j=(i-1); j>0; j--)
        cout << x[j];
        

    return 0;

}

I know it's because I have declared x[i] as an integer, so that's why it's happening, but I don't know how to fix this problem.我知道这是因为我已将 x[i] 声明为 integer,所以这就是它发生的原因,但我不知道如何解决此问题。

To print an ASCII code as a character, you cast it to char.要将 ASCII 代码打印为字符,可以将其转换为 char。 So, instead of所以,而不是

cout << x[j];

You can do你可以做

cout << static_cast<char>(x[j]);

However, you currently leave digits below 10 as a number, which after casting to char would be wrong.但是,您目前将 10 以下的数字保留为数字,这在转换为 char 后将是错误的。 You could fix that by adding '0' to rem if it's less than 10.如果它小于 10,你可以通过在 rem 中添加'0'来解决这个问题。

Another possibility is changing the type of x from int to char;另一种可能性是将 x 的类型从 int 更改为 char; that way, you wouldn't have to cast.这样,您就不必施法了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM