如果可以准确翻译,我正在编写一个代码来将十进制从一元转换为二进制,或者如果不能,则返回错误消息。以下是我的代码。我对小数错误感到困惑。一步,n之前是1.12,temp是1,但是输出是0.12001,如何避免这种错误呢?
list<bool> binary_decimal(double n, bool& flag){
list<bool> li;
list<double> left;
flag = true;
n = n - (int)n;
left.push_back(n);
while(n){
n = n * 2;
cout << "n before " << n << endl; //test area
li.push_back(n >= 1);
int temp = (int)n;
cout << "temp " << temp << endl; // test area
n = n - temp;
cout << "n now = " << n << endl; //test area
for(list<double>:: iterator it = left.begin(); it != left.end(); it++){
if(*it == n){
cout << "error!";
flag = false;
return li;
}
}
left.push_back(n);
}
return li;
}