【问题标题】:cout prints the incorrect valuecout 打印不正确的值
【发布时间】:2018-06-25 19:21:30
【问题描述】:

所以,我正在尝试制作一个基本的 C++ 程序来转换 Base 10 -> Base 16

while(true){
    int input;
    cout << "Enter the base 10 number\n";
    cin >> input;
    cout << "The hex form of " << input << " is: ";
    int decimal = input;
    cout << hex << uppercase << decimal << "\n";
    decimal = NULL;
    input = NULL;
    Sleep(3000);
}

在第一次运行时,它可以工作。例如,如果我输入 7331,我会得到:

The hex form of 7331 is 1CA3

但如果我第二次尝试(使用相同的输入)我会得到:

The hex form of 1CA3 is 1CA3

我可以尝试使用任何整数输入,它在第一次运行时运行良好,但之后它将基数为 16 的数字输入两次。

【问题讨论】:

  • 这实际上不是我的代码,我只是想表明它包含在一个循环中。让我解决
  • Close-voter:这有什么不清楚的地方?我发现这个问题很清楚,OP 提到了他们的输入、输出和他们的期望。这个例子或多或少是完整的。
  • 有些流操作符是sticky,有些不是。 std::hex 是粘性。
  • 避免using namespace std

标签: c++ hex cin cout


【解决方案1】:

你甚至可以缩短你的代码:

while (true)
{
    int input;

    cout << "Enter the base 10 number: ";
    cin >> input;
    cout << "The hex form of " << dec << input << " is: ";
    cout << hex << uppercase << input << "\n";

    Sleep(3000);
}

【讨论】:

  • 是的,我最初就是这样。我添加了其他东西来尝试“清除”我的变量。
【解决方案2】:

您需要重置直播。当您将std::hex 应用于std::cout 时,它会永久应用于流(std::cout),您需要将其重置。您可以简单地将您的程序更改为:

cout << "The hex form of " << std::dec << input << " is: ";

【讨论】:

    【解决方案3】:

    你的修复:

    cout << "The hex form of "<< dec << input << " is: ";
    

    【讨论】:

      猜你喜欢
      • 2022-09-11
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 2011-12-25
      • 2014-05-17
      相关资源
      最近更新 更多