0

I made a simple example for counting decimal points but it doesn't stop and doesn't give me the right answer here's my code:

double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
    {
        b*=10;            
        count++;          
    } 
        cout<<count;

the answer is supposed to be:

3

but instead the while loop keeps running Indefinitely .. what's wrong with my code?

Dreamer
  • 25
  • 5
  • I think you forgot to actually substract from b. Add b-=10 above b*=10, and it works fine. – Aart Stuurman Sep 15 '14 at 00:42
  • 3
    Possible duplicate: http://stackoverflow.com/questions/17837654/count-number-of-digits-after-in-floating-point-numbers – benipalj Sep 15 '14 at 00:44
  • It's not the same @cyrus – Dreamer Sep 15 '14 at 01:01
  • @user3397351 Did my [answer](http://stackoverflow.com/a/25836106/2809095) to your previous question not work? For `double` all you have to do is change the constants (Mantissa 23 -> 52, Exponent 8 -> 11), the width of the variables (`uint32_t` -> `uint64_t`) and `__builtin_ctz()` -> `__builtin_ctzll()`... If you're on MSVC you can use `#include ` then `_BitScanForward(&umanctz, value)`. – Iwillnotexist Idonotexist Sep 15 '14 at 16:43

2 Answers2

1

You should have checked the INT_MAX first. The number would be different. It depends on whether you are running the code on a 32-bit or 64-bit machine. If it is way smaller than your initial b, you would definitely end up in the infinite loop. For example, the max of short integer type is 32767. In that case, the condition of your loop would be like this: 76327741.125 - some negative number, larger than 0. however, in the loop, you increased the value of b. The next time, when we hit the condition line, it would be something like this: 76327741.125*10 - some negative number

Decipher
  • 194
  • 2
  • 11
  • Do you mean `while(b - (int)b > 0.0) { b = b - (int)b; b*=10; count++; } ` – Dreamer Sep 15 '14 at 00:56
  • explanation in details given @user3397351 – Decipher Sep 15 '14 at 01:01
  • No the compiler subtract right 76327741.125-76327741 and the two values becomes the same after three operations `*10` but i don't know why it just don't stop when `b-int(b)=0` – Dreamer Sep 15 '14 at 01:06
  • 2
    What he means is that, after the first `b *= 10`, the value of `b` becomes `763277411.25`, which is greater than the maximum value an `int` can have (`INT_MAX`) on common PCs (2^32-1). – André Sassi Sep 15 '14 at 01:09
  • @user3397351 u probably should have put (int)b in the watch window first and check its value. sure u r gonna find something helpful – Decipher Sep 15 '14 at 01:11
0

You should probably set b to be b - int(b), to make sure it doesn't keep increasing (and potentially overflowing).

double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
  b = b - int(b); // Note the change here.
  b*=10;
  count++;          
} 
cout<<count;
Sidd
  • 1,168
  • 2
  • 10
  • 27