[英]C++ base 10 to base 2 logic error
I am doing a basic program to convert number from base 10 to base 2. I got this code: 我正在做一个基本程序,将数字从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;
}
Everything is good with certain numbers, but, if I try to convert the number 11 to base 2, I get 1101, if I try 56 I get 100011... I know is a logic problem and I am limited to basic algoritms and functions :(... any ideas? 使用某些数字,一切都很好,但是,如果我尝试将数字11转换为基数2,我将得到1101,如果我尝试56将我得到100011 ...我知道这是一个逻辑问题,我仅限于基本的算法和函数:(... 有任何想法吗?
you can use this, it is simpler and cleaner:. 您可以使用它,它更简单,更干净: Use
std::reverse
from <algorithm>
to reverse the result. 从
<algorithm>
使用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;
}
However even much cleaner version could be: 但是, 更干净的版本可能是:
#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());
}
using above, result of 使用上面的结果
binary(11);
binary(56);
is 是
00000000000000000000000000001011
00000000000000000000000000001010
00000000000000000000000000111000
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.