2016-12-24 89 views
-5

我想将二进制数更改为十进制数。更改二进制数>使用For循环的十进制数

我的问题是我的程序不会进入即使for循环,因此我的总和总是0.我不知道我的for循环的错误在哪里。

我的想法是,对于像1010这样的数字,我将它除以10得到最后一位数字为0,然后将它与2^0相乘,然后将1010除以10得到101,循环继续。

这里是我到目前为止已经试过:

cout<<"Please Enter a Binary Digit Number"<<endl; 
cin>>num; 
sum=0; 
x=0; 

for (int i=num; i/10 == 0; i/10) { 
    sum+=num%10*2^x; 
    num/=10; 
    x++; 
} 

cout<<sum; 
+2

[你知道是什么'^'操作符在C++中表示?](http://stackoverflow.com/q/4843304/995714) –

回答

1

想必您邀请用户在控制台输入的二进制字符串。在这种情况下,您必须将这些数字收集为一串字符。

更类似的东西?

using namespace std; 
std::string bin; 
cout<<"Please Enter a Binary Digit Number"<<endl; 
cin>>bin; 

int sum=0; 
int bit=1; 
for (auto current = std::rbegin(bin) ; current != std::rend(bin) ; ++current, bit <<= 1) 
{ 
    if (*current != '0') 
     sum |= bit; 
} 

cout<<sum << std::endl; 

或C++ 11之前(我认为这是一个学校项目 - 他们很可能有过时套件):

for (auto current = bin.rbegin() ; current != bin.rend() ; ++current, bit <<= 1) 
{ 
    if (*current != '0') 
     sum |= bit; 
} 
0
working:- 

    #include<iostream> 
    using namespace std; 
    int num,sum,x; 
    int main() 
    { 
    cout<<"Please Enter a Binary Digit Number"<<endl; 
    cin>>num; 
    sum=0; 
    x=0; 

    long base=1,dec=0; 
//Binary number stored in num variable will be in loop until its value reduces to 0 
    while(num>0) 
    { 

     sum=num%10; 
//decimal value summed ip on every iteration 
     dec = dec + sum * base; 
//in every iteration power of 2 increases 
     base = base * 2; 
//remaining binary number to be converted to decimal 
     num = num/10; 
     x++; 
    } 

    cout<<dec; 
    return 0; 
    } 
+0

为什么它工作?它如何解决OP的问题? IOW,没有澄清或评论的代码是毫无价值的。 –

+0

该代码已被编辑谢谢,托马斯和圣诞快乐 – Codesingh

相关问题