0

我是 C++ 的初学者,今天我想自己写一个小程序,将十进制数转换为二进制数。代码看起来像这样:

#include <iostream>
void binaryConvert(int);
int main() {
    using namespace std;
    cout << "Enter decimal number for conversion:" << endl;
    int dec;
    cin >> dec;
    binaryConvert(dec);
}
void binaryConvert(int number) {
    using namespace std;
    while(number > 0) {
        int bin = number % 2;
        number /= 2;
        cout << bin;
    }
}

从逻辑上讲,这个程序会以相反的方式打印二进制文件。我花了很长时间试图弄清楚如何反转二进制数字的顺序,以便在遇到这段代码时二进制数字会以正确的方式出现:

void binaryConvert(int number) {
    using namespace std;
    if(number > 0) {
        int bin = number % 2;
        number /= 2;
        binaryConvert(number);
        cout << bin;
    }
}

我知道这可能是一个愚蠢的问题(我是一个绝对的初学者),但我不明白为什么这段代码会以正确的顺序打印这些位。此外,如果在 cout 执行之前再次调用该函数,那么这些位实际上是如何被打印出来的?

4

6 回答 6

2

基本上是因为在“binaryConvert”之后调用了“cout”。这就像将所有位放在一个堆栈中,然后打印它们。

于 2012-11-25T17:45:32.043 回答
0

它利用递归,直到基本情况被击中(数字<= 0)才打印最后的bin,然后它将上升到堆栈跟踪。

于 2012-11-25T17:46:52.233 回答
0

这个函数是一个递归函数。它以递归方式调用自己,先打印出最低有效数字,然后再打印出最高有效数字。

于 2012-11-25T17:47:32.463 回答
0
int num;
string BinaryRepresentation="";
cout<<"Input:";
cin>>num;
string  newstring= "";

bool h;
h = true;

while(h){
    BinaryRepresentation += boost::lexical_cast<std::string>( num % 2 );
    num = num / 2;
    if ( num < 1){
        h = false;
    }
}
for ( int i = BinaryRepresentation.size() - 1; i >= 0; i--){
    newstring += BinaryRepresentation[i];

}
     cout<< "Binary Representation: " << newstring <<endl;

}

该程序的主要思想是找到数字的提示并将数字除以2并继续重复相同的过程直到数字变为0。您需要反转字符串以获得二进制等价物输入的号码。

于 2014-08-24T04:48:48.957 回答
0

正如您正确提到的那样,您的程序在输出时反转了二进制文件。以正确的顺序将二进制文件放入第二个代码仅在获得最后一位后才开始提供输出。输出的顺序是 bin 到 bin,因此我们获得了所需的输出。以下代码可能有助于您进一步理解:http: //ideone.com/Qm0m7L

void binaryConvert(int number) {
    if(number > 0) {
        int bin = number % 2;
        number /= 2;
        cout << bin<<" one"<<endl;
        binaryConvert(number);
        cout << bin<<" two"<<endl;
    }
}

得到的输出是:

0 one
0 one
0 one
1 one
1 two
0 two
0 two
0 two

“一”之前的输出是您的程序所给出的。我希望你能理解其中的区别。

于 2014-08-26T12:58:41.883 回答
0

当我在网上搜索从十进制转换为二进制时,没有找到一个简单易懂的解决方案。所以我自己写了一个程序。就这样吧。

 #include <iostream>
#include <string>
#include <sstream>

using namespace std;
void dtobin(int n)
{
   ostringstream oss;
   string st="";
if(n<0)
{
    cout<<"Number is negative";
    return;
}
   int r;
while(n!=1)
{

    r=n%2;
    oss<<st<<r;
    n/=2;
}
oss<<st<<1;
st=oss.str();
cout<<st;
//To reverse the string
int len=st.length();
int j=len-1;
char x;
for(int i=0;i<=len/2-1;i++)
{
    x=st[i];
    st[i]=st[j];
    st[j]=x;
    --j;
}
cout<<endl<<st;
}


  int main()
{
  int n;
  cout<<"ENTER THE NUMBER";
  cin>>n;
  dtobin(n);
  return 0;
}
于 2015-12-31T17:21:34.207 回答