C++十进制转二进制(含小数部分)

  首先得知道十进制如何转二进制,下面给个例子就明白了。

假设给一个十进制数167.25,将它转为二进制表示

首先将小数点前即整数部分进行转换。

167=83*2 + 1

83=41*2 + 1

41=20*2 + 1

20=10*2 + 0

10=5*2 + 0

5=2*2 + 1

2=1*2 + 0

1=0*2 +1

结果为:1010 0111(从这里可知结果为先进后出,最先得出的结果在最后输出)

接下来是小数部分。

0.25*2=0.5

0.5*2=1

小数结果为01(只取乘2后的整数位,小数位为0时停止;可知结果为先进先出,最先得出的结果最先输出)

  根据上面的例子,很明显整数部分的转换要用到栈,而小数部分的转换需要用到队列。

  对于特殊情况,如循环小数,则需要限制输出(如添加变量t++表示小数位数)

以下是代码

#include <iostream>
#include <stack>
#include <queue>
using namespace std;

void binary(double num)
{
	stack<int>list;
	queue<int>listb;
	int front = num;
	double last = num - front;
	
	if (front != 0)
	{
		while (front != 0)
		{
			if (front % 2 == 1)
			{
				list.push(1);
				front = (front - 1) / 2;
			}
			else if (front % 2 == 0)
			{
				list.push(0);
				front = front / 2;
			}
		}
		while (!list.empty())
		{
			cout << list.top();
			list.pop();
		}
	}
	else
	{
		list.push(0);
	}

	if (last != 0)
	{
		cout << ".";
		while (last != 0)
		{
			last = last * 2;
			if (last >= 1)
			{
				last--;
				listb.push(1);
			}
			else
			{
				listb.push(0);
			}
		}
		while (!listb.empty())
		{
			cout << listb.front();
			listb.pop();
		}
	}
	cout << endl;
}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		double num;
		cin >> num;
		binary(num);
	}
}

  附:二进制转十进制比较麻烦,可以定义一个char类型的栈来处理整数(栈顶元素乘2的n次方最后相加,n表当前位数);小数部分用char类型的队列处理即可。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值