careercup5.2

来源:互联网 发布:唐小僧 以数据和科技 编辑:程序博客网 时间:2024/06/15 10:01

判错搞麻烦了。。

/*Given a (decimal - e g  3  72) number that is passed in as a string, print the binary rep-resentationIf the number can not be represented accurately in binary, print “ERROR” */#include <iostream>#include <string>#include <bitset>using namespace std;string n;bool numtobit(string k){bool dec = true;string int_part;string float_part ="0.";for(int i =0; i<k.length(); i++){if((!dec && k[i] == '.') || ((k[i]>'9' || k[i]<'0')&& k[i]!='.'))return 0;if(k[i] == '.'){  dec = false;  continue;}if(dec) int_part += k[i];else float_part +=k[i];}int a = atoi(int_part.c_str());float b = atof(float_part.c_str());int i = 0;while(a>0){  n = char(a%2+48) + n;  a /= 2;}if(b>0){n = n + '.';while(b!= 0){   b *=2;   if( b >=1){   n += '1';   b -= 1;   }else n += '0';}}return 1;}int main(){string k = "113.8125";if(!numtobit(k))cout<<"ERROR!"<<endl;else cout<<n<<endl;}