程序员面试金典——5.2二进制小数
Solution1:我的答案,感觉就挺好。。。
class BinDecimal {
public:
string printBin(double num) { //0到1之间的实数,乘2取整,顺序排列
// write code here
if(num == 0.0)
return "0";
else if(num == 1.0)
return "1";
string res("0.");
int Integer = 0;
double n1 = 0.0, temp_num = num;// n1 = num * 2, n2 = n1 - (int)n1
while(temp_num) {
n1 = temp_num * 2;
Integer = (int)n1; //取出整数部分
res += to_string(Integer);
temp_num = n1 - Integer;
if(res.size() == 32 && temp_num != 0.0)
return "Error";
}
return res;
}
};