簡體   English   中英

將 int 轉換為十六進制時,我們是否必須將其轉換為字符串,還是可以將其保留為 int 類型? c++

[英]When converting an int to a hex, do we have to convert it to a string or can we keep it a type int? c++

對於我所在的系統 I class,他們希望我們輸入一個數字並將其轉換為十六進制。 我知道我可以這樣做:

cin >> std::hex >> x;

但是對於這個程序,我想在之后嘗試做,因為有一個if語句。

這是我擁有的代碼。

cout << "Enter an integer value between 0 and 255 for Green: ";
cin >> G;
if (G > 255 || G < 0)
{
    cout << "The number you have entered is bigger than 255 or smaller than 0.";
}
else 
{
    G = std::hex >> G;
}    

輸入一個數字並將其轉換為十六進制。

這滿足了要求。 讀取十進制數(0 到 255),將其存儲在 integer 中。 使用 integer 顯示輸入值的十進制和十六進制格式。

#include <iostream>
int main() {
    int G;

    while (true)
    {
        std::cout << "Enter an integer value between 0 and 255 for Green: ";
        std::cin >> G;
        if (G > 255 || G < 0)
        {
            std::cout << "The number you have entered is bigger" \
                << " than 255 or smaller than 0.\n";
        }
        else
        {
            break;
        }
    }

    std::cout<< "G is " << G << " in decimal and 0x" << std::hex << G << " in hex.\n";
}

暫無
暫無

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

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