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

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

#include 
#include 
#include 
#include 
using namespace std;

template  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';

}


你可能感兴趣的:(程序员面试金典)