【问题标题】:C++ base 10 to base 2 logic errorC++ base 10 到 base 2 逻辑错误
【发布时间】:2013-09-28 20:16:51
【问题描述】:

我正在做一个基本的程序来将数字从 10 转换为 2。我得到了这个代码:

#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
    int num=0, coc=0, res=0, div=0;
    printf ("Write a base 10 number\n");
    scanf ("%d", &num);
    div=num%2;
    printf ("The base 2 value is:\n");
    if(div==1)
    {
        coc=num/2;
        res=num%2;
        while(coc>=1)
        {
            printf ("%d", res);
            res=coc%2;
            coc=coc/2;
        }
        if(coc<1)
        {
            printf ("1");
        }
    }
    else
    {
        printf ("1");
         coc=num/2;
        res=num%2;
        while(coc>=1)
        {
            printf ("%d", res);
            res=coc%2;
            coc=coc/2;
        }
    }
    printf ("\n");
    system ("PAUSE");
    return EXIT_SUCCESS;
}

对于某些数字,一切都很好,但是,如果我尝试将数字 11 转换为基数 2,我得到 1101,如果我尝试 56,我得到 100011...我知道这是一个逻辑问题,我仅限于基本算法和函数:(...有什么想法吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow!要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,你就发现了你的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
  • @computer 是的,我可以使用 bitset。
  • @user2827058 请查看更新

标签: c++ logic decimal base


【解决方案1】:

你可以使用它,它更简单更干净:。使用 &lt;algorithm&gt; 中的 std::reverse 来反转结果。

#include <algorithm>
#include <string>
using namespace std;

string DecToBin(int number)
{
    string result = "";

    do
    {
        if ( (number & 1) == 0 )
            result += "0";
        else
            result += "1";

        number >>= 1;
    } while ( number );

    reverse(result.begin(), result.end());
    return result;
} 

但是,即使是 更简洁 的版本也可能是:

#include<bitset>

void binary(int i) {
    std::bitset<8*sizeof(int)> b = i;
    std::string s = b.to_string<char>();
    printf("\n%s",s.c_str());
}

使用上面的结果

binary(11);
binary(56);

00000000000000000000000000001011

00000000000000000000000000111000

甚至更好:

#include <iostream>

void binary(int i) {
    std::bitset<8*sizeof(int)> b = i;//assume 8-bit byte,Stroustrup "C++..."&22.2
    std::cout<<b;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 2012-03-22
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多