Two ways to pay attention to the logical details!
//Title Description////There is a real number between 0 and 1, and the type is double, which returns its binary representation. Returns "Error" if the number cannot be represented exactly in a 32-bit binary representation. //given a double num, which represents a real number from 0 to 1, return a string representing the binary representation of the numbers or "Error". //Test Examples://0.625//return: 0.101//two methods, forward and reverse#include<iostream>using namespacestd; #include<string>classBindecimal { Public: stringPrintbin (Doublenum) { //Write code here Double Base=2.W; stringstr ="0."; while(num) {if(num>=Base) {num-=Base; STR+="1"; } Else{str+="0"; } if(Str.size () >= +) {str="Error"; Break; } //num-= base; Logic Error Base=Base/2; } returnstr; }};classBindecimal { Public: stringPrintbin (Doublenum) { //Write code here stringstr ="0."; for(inti =0; I < +; i++) {num*=2; if(num>=1) {str+="1"; Num-=1.0; } Else{str+="0"; } if(num<=0.0) { returnstr; } } if(num>0.0) { return "Error"; } returnstr; }};intMain () {Doubleval =0.625; Bindecimal b; cout<<b.printbin (val) <<Endl; return 0;}
Binary representation of decimals