Search code examples
c++decimal-point

Error in while loop?


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?


Solution

  • 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;