简体   繁体   中英

Counting number of digits in a double C++

I'm using a while loop to count the number of digits in my input.

So my input was 1.525

length = 0;
num = num - int(num);
while ( num >= .0001 ) {
    num = num * 10;
    length = length + 1;
    num = num - int(num); }

When i do

cout << "\n\nLength: " << length << "\n";

The answer I get is 51 and other numbers give me an asnwear of 49 or something that is obviously wrong. Is it the way c++ works or is it just my mistake. Thank you.

double and float can't always hold precisely the values you try to store in them, thats not how they work. In many cases they will store an approximate value, that usually can be rounded up to what you meant to store there in the first place, but not exactly. Thats why you are getting those results.

You can use string or char array to store the the number inputed. it can precisely count the length. float double store a approximate value, you can reference here .

Floating point numbers cannot store the decimal 1.525 precisely but if you use round instead of int cast and use fabs when comparing against the tolerance to protect against negative numbers you will get something you might be happy with:

num -= round(num);
while(fabs(num) >= .0001) {
  num *= 10;
  ++length;
  num -= round(num); 
}

If you are happy to accept that 1.9999999 has the same number of digits as 2.0.

Generally, trying to find the number of digits in a floating point number is going to be a bit meaningless because it is not stored as decimal digits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM