簡體   English   中英

從十進制基數轉換為十六進制基數c ++

[英]converting from decimal base to hexadecimal base c++

我要從大於10(11到16)的基數轉換。 此代碼只能轉換為2-9的基數。 我如何轉換說10的299 = 16的12B,15的14E,13的1A0 ......同樣。 我的代碼應該在哪里/如何放置? 先感謝您。

using namespace std;

int main()
{
    stack <int> mystack;
    int input;
    int base;

    cout << "Please enter an integer to be converted (base 10): ";
    cin >> input;
    cout << "Base (2 to 16): ";
    cin >> base;

    do {
        int x = input % base;
        mystack.push(x);
    } while (input = input / base);

    cout << "\nThe base " << base << " is:\n";
    while (!mystack.empty())
    {
        int x = mystack.top();
        cout << x << " ";
        mystack.pop();
    }
    cout << "\n\n";
}

您的轉換代碼是正確的: mystack包含正確的數字,但順序相反。

但是,您的打印代碼是錯誤的: cout << x << " "; xint將打印數字,對於11或以上的基數,您還需要字母。

一種方法是制作一個數字string ,並將x用作索引:

std::string digits("0123456789ABCDEF");
...
while (!mystack.empty()) {
    int x = mystack.top();
    cout << digits[x] << " ";
    mystack.pop();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM