字符串十进制小数转换成字符串二进制小数

输入一个字符串,字符串内容为十进制小数,将其转换为二进制小数,如果不能转换则返回error。

#include <iostream>
#include <math.h>
#include <string>
#include <sstream>
using namespace std;

template <class T> string m_toStr(T tmp)
{
    stringstream ss;
    ss << tmp;
    return ss.str();
}


int main() {
	string n="3.75";
	stringstream stream;
	int intPart;
	double decPart;
	stream << n.substr(0,n.find('.'));
	stream >> intPart;
	stream.clear();
	stream << n.substr(n.find('.'),n.length());
	stream >> decPart;

	string int_string = "";
	while(intPart > 0){
		int r = intPart % 2;
		intPart >>=1;
		int_string = m_toStr(r) + int_string;
	}
	string dec_string = "";
	while(decPart > 0){
		if(dec_string.size() > 32) {
			cout<<"error";
			return 0;
		}
		if(decPart == 1){
			dec_string += m_toStr(decPart);
			break;
		}
		double r = decPart * 2;
		if(r>=1){
			dec_string += '1';
			decPart = r - 1;
		}else{
			dec_string +='0';
			decPart = r;
		}
	}


	cout<< int_string +'.'+dec_string <<'\n';

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值