2016-12-24 92 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

相關問題