您的位置:首页 > 其它

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

2016-10-09 11:36 281 查看
输入一个字符串,字符串内容为十进制小数,将其转换为二进制小数,如果不能转换则返回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';

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符转换