C++ 如何将十进制数转换为二进制数?

标签 c++ loops for-loop binary decimal

我的任务是编写一些代码来接受用户输入并将数字转换为二进制数。到目前为止,我已经编写了一些代码,但遇到了一个问题。我必须使用 for 循环和商余法。当我输出余数(二进制)时,它没有打印最后一位数字。

我要问的问题是:我必须在 for 循环中更改什么才能打印出二进制数的最后一位?

int main()
{
    int num;
    int rem;

    cout << "Please enter a number: ";
    cin >> num;

    for (int i = 0; i <= (num + 1); i++)
    {
        num /= 2;
        rem = num % 2;
        cout << rem;
    }

    _getch();
    return 0;
} 

感谢任何帮助,谢谢!

最佳答案

当您通过将 num 除以 2 开始您的算法时,您丢失了最后一个二进制数。为避免此问题,您应该交换指令 num/= 2;rem = num % 2;

您的循环也迭代了太多次:实际上您可以在 num == 0 时停止。以下代码对 <= 0 的输入无效。

int main()
{
    int num;
    int rem;

    cout << "Please enter a number: ";
    cin >> num;

    while (num != 0)
    {
        rem = num % 2;
        num /= 2;
        cout << rem;
    }
    cout << std::endl;

    return 0;
} 

如果你想以正确的顺序写入它,你应该首先计算你的数字以 2 为底数的对数。以下解决方案使用以“1”开头的数字 index 并且具有'0' 之后:

int main()
{
    int num;
    int rem;

    cout << "Please enter a number: ";
    cin >> num;

    if (num > 0) {
      int index = 1;
      while (index <= num)
         index *= 2;
      index /= 2;

      do {
        if (num >= index) {
           cout << '1';
           num -= index;
        }
        else
           cout << '0';
        index /= 2;
      } while (index > 0);
      cout << std::endl;
    }
    else
      cout << '0';

    cout << endl;
    return 0;
} 

关于C++ 如何将十进制数转换为二进制数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39947309/

相关文章:

c++ - 输出指针的 const 前缀

c++ - 在 O(logn) 中计算 C++ 中元素的下限

java - 从名称为variableX的变量中检索数据 - Java

javascript - 为什么我的 fadeToggle 在某一类上循环?

c++ - 将亚洲和其他字符放入 Visual Studio 源代码中

c++ - 更改sublime text的默认输入源

java - 在 Mule 3.4 中模拟 while 循环

Java - For循环只运行一次

arrays - 将旧的 C for 循环更改为新的 Swift 循环

C++ 11:第二个元素的范围循环矢量?