Given a(decimal -e.g. 3.72)number that is passed in as a string, print the binary representation. If the number can not be represented accurately in binary, print "ERROR"
?
整數部分:
? ? 對2取余,然后向右移動一位,重復直到整數部分變為0
小數部分:
? ? 乘以2,看結果是否大于1,大于1則2^-1位上位1,否則為0。如果大于1,將結果減1再乘以2,否則直接乘以2,繼續判斷,直到小數部分超過32位,返回ERROR
? ? 例如:0.75d = 0.11b,乘以2實際上相當于左移,結果大于1,則說明2^-1位上是1,然后減1,繼續乘以2,結果等于1,說明2^-2上是1,且后面沒有小數了。
#include<iostream> #include<string> #include<stdlib.h> using namespace std;string func(const string &str) {string strInt;string strDou;string::size_type idx = str.find('.'); if(idx == string::npos){strInt = str;}else{strInt = str.substr(0,idx);strDou = str.substr(idx);}int intPart = atoi(strInt.c_str());double douPart;if(!strDou.empty()){douPart = atof(strDou.c_str());}else{douPart = 0.0;}string strIntB,strDouB;while(intPart!=0){if((intPart&1)>0){strIntB = '1'+strIntB;}else{strIntB = '0'+strIntB;}intPart=intPart>>1;}while(!(douPart>-10e-15 && douPart<10e-15)){if(douPart*2>1){strDouB = '1'+strDouB;douPart = douPart*2-1;}else if((douPart*2-1)>-10e-15 && (douPart*2-1)<10e-15){strDouB = '1'+strDouB;break;}else{strDouB = '0'+strDouB;}if(strDouB.size()>32){return "ERROR";}}if(strDouB.empty()){return strIntB;}else{return (strIntB+'.'+strDouB);} }int main() {string str("3.75");cout<<func(str)<<endl;return 0; }
?