C ++中给定数字的二进制表示
二进制数是仅由两位数字0和1组成的数字。例如01010111。
有多种方式来表示给定数字的二进制形式。
递归方法
此方法用于使用递归以二进制形式表示数字。
算法
Step 1 : if number > 1. Follow step 2 and 3. Step 2 : push the number to a stand. Step 3 : call function recursively with number/2 Step 4 : pop number from stack and print remainder by dividing it by 2.
示例
#include<iostream>
using namespace std;
void tobinary(unsigned number){
if (number > 1)
tobinary(number/2);
cout << number % 2;
}
int main(){
int n = 6;
cout<<"数字 "<<n<<" 其二进制表示为 ";
tobinary(n);
n = 12;
cout<<"\n数字 "<<n<<" 其二进制表示为 ";
tobinary(n);
}输出结果
数字 6 其二进制表示为 110 数字 12 其二进制表示为 1100
热门推荐
10 最真的新春祝福语简短
11 日语送考祝福语简短
12 弟弟生日祝福语简短的话
13 38节贺卡简短祝福语
14 关于开车的祝福语简短
15 写给情侣祝福语 浪漫简短
16 初升高祝福语家长简短
17 班级集体生日祝福语简短
18 给婴儿祝福语简短的话