【问题标题】:Convert decimal to hex, can't find my logic error将十进制转换为十六进制,找不到我的逻辑错误
【发布时间】:2015-06-15 16:02:32
【问题描述】:

我是 C++ 和一般编码的新手。我知道有逻辑错误,但我无法识别它。我正在尝试输入十进制,并将输出连接为十六进制。即使控制变量显然还不是 0,它似乎也只运行一次循环。

int main()
{
    long rem = 0,
    int hex = 0; 
    cout << "enter the number to convert ";
    cin >> rem;     
    hex = rem / 16;
    while (rem > 0)
    {
        rem = rem % 16;
        hex = hex + rem;
        cout << hex << "" << rem << endl;
        rem = rem / 16;
    }
    return 0;
}

【问题讨论】:

  • 如果您只想以十六进制打印数字,请尝试:stackoverflow.com/questions/3649026/…
  • cout &lt;&lt; hex 应该是 cout &lt;&lt; std::hex。你的实际代码输出你的局部变量hex

标签: c++


【解决方案1】:

如果您只需要以十六进制输出值,那么您可以使用std::hex 格式标志。例如:

long rem = 16;
std::cout << std::hex << rem << std::endl; //prints 10

Live Demo

【讨论】:

    【解决方案2】:
    #include <iostream>
    using namespace std;
    int main() {
        // you have to declare variable independently when you declare different type variable
        long rem = 0;  // you typed (,)
        int hex = 0;
    
        cout << "enter the number to convert ";
        cin >> rem;
    
        hex = rem / 16;
    
        while (rem > 0)
        {
            rem = rem % 16; // after this, rem is lower then 16 (remain operator)
            hex = hex + rem;
            cout << hex << "" << rem << endl;
            rem = rem / 16; // so rem must be 0 because rem is lower then 16
        }
    
        return 0;
    }
    

    实际上,即使我解决了您的问题,您的代码也不能正常工作,但这就是您的循环只运行 1 次的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-11
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      相关资源
      最近更新 更多