h**o 发帖数: 548 | 1 given 1/10, 1/3.。。问能否 represented exactly in base 2?
怎么做? | J**9 发帖数: 835 | 2 check whether it can be equal 1/2 + 1/4 + 1/8 + ...
see /// below
/**
* Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a
double, print
* the binary representation. If the number c*annot be represented
accurately in binary
* with at most 32 characters, print "ERROR."
* hkBitsDoubleBits(): 0.720000 = 0.101110000101000111101011100001
* hkBitsDoubleBits(): 0.687500 = 0.1011
* hkBitsDoubleBits(): 0.500000 = 0.1
*/
char *hkBitsDoubleBits(double num, char *str, int maxSize)
{
if (!str)
return NULL;
if (num>=1.0 || num<0.0)
{
strcpy(str, "ERROR");
return str;
}
char *p = str;
*p++ = '0';
*p++ = '.';
maxSize -= 2;
while((num>0.0000000000001) && (maxSize>0))
{
double temp = 2.0 * num;
if (temp>=1.0)
{
*p++ = '1';
num = temp - 1.0;
/// if temp == 1.0, then can be represented exactly
}
else
{
*p++ = '0';
num = temp;
}
maxSize--;
}
*p = '\0';
return str;
} | d**********x 发帖数: 4083 | 3 why don't you just check the denomanitor and see if it is 2^n?
for m/10^n, playing with gcd(m, 10^n) will give you the answer
【在 J**9 的大作中提到】 : check whether it can be equal 1/2 + 1/4 + 1/8 + ... : see /// below : /** : * Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a : double, print : * the binary representation. If the number c*annot be represented : accurately in binary : * with at most 32 characters, print "ERROR." : * hkBitsDoubleBits(): 0.720000 = 0.101110000101000111101011100001 : * hkBitsDoubleBits(): 0.687500 = 0.1011
|
|