c++十进制转二进制(几种解法)

1.累加

#include <iostream>
#include <cmath>
using namespace std;
int num (int a)
{
    int b = 0;
    int i = 0;
    int result = 0;
    for (; a >= 2;i++)
    {
        b = a % 2;
        a /= 2;
        result += (b * pow(10,i));
    }
    result += (a* pow(10,i));
    return result;
}
int main()
{
    int n;
    cin >>n;
    cout <<num(n);
    return 0;
}

以下摘自
https://blog.csdn.net/huplion/article/details/43016599?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158364201419195239814797%2522%252C%2522scm%2522%253A%252220140713.130056874…%2522%257D&request_id=158364201419195239814797&biz_id=0&utm_source=distribute.pc_search_result.none-task
纯属为了以后查看方便(^ _ ^)

2.利用递归

#include<iostream>
using namespace std;
void f(int n)
{
 if (n > 0)
 {
  f(n / 2);
  cout << n % 2;
 }
}
int main()
{
 int n;
 cout << "请输入一个整数:" << endl;
 cin >> n;
 f(n);
 return 0;
}

3.利用数组

#include<iostream>
using namespace std;
int main()
{
 int s[100];
 int count=0,n;
 cout << "请输入一个正整数:" << endl;
 cin >> n;
 while (n != 0)
 {
  s[++count] = n % 2;
  n = n / 2;
 }
 for (; count > 0; count--)
 {
  cout << s[count];
 }
 return 0;
}

4.利用栈

#include<iostream>
#include<stack>
using namespace std;
stack<int>STD;
int main()
{
 int n;
 cout << "请输入一个正整数:" << endl;
 cin >> n;
 while (n != 0)
 {
  STD.push(n % 2);
  n = n / 2;
 }
 while (!STD.empty())
 {
  cout << STD.top();
  STD.pop();
 }
 return 0;
}
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值