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 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短