实验思路:一个数要转换成二进制的方法就是用这个数除以2,得到余数,而得到的商再除以2,得到余数,各个余数从最后一个到第一个的顺序排列,而这时为了这个最后一个余数在高位,而第一个余数在低位的顺序,需要借助递归,因为递归是栈的应用,有先进后出,后进先出的特性,这时可解决这样一个问题。
#include <iostream>
using namespace std;
void Binary(int i);
int main(){
int a;
cout << "Please enter a positive integer within 1000 " << endl;
cin >> a;
if(a > 1000 || a <= 0)
cout << "Input error" << endl;
else{
cout <<"The binary number of this number is ";
Binary(a);
}
return 0;
}
void Binary(int i){
int a;
a = i % 2;
i /= 2;
if(0 != i)
Binary(i);
cout << a;
return;
}