1
我正在編寫一個代碼,用於將一位小數從一元轉換爲二進制,如果它可以準確翻譯,或者返回錯誤消息(如果不能)。以下是我的代碼。我對十進制錯誤感到困惑。一步之前,n是1.12,temp是1,但輸出是0.12001,如何避免這種錯誤?C++中的十進制精度錯誤
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;
}
什麼是*一元*號碼? –
@ZacHowland http://en.wikipedia.org/wiki/Unary_numeral_system –
雖然我不確定他是否正確使用該術語。一個'double'怎麼可能是一元的? – crashmstr