Reputation: 11
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.
Upvotes: 0
Views: 3121
Reputation: 15334
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.
Upvotes: 0
Reputation: 51
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.
Upvotes: 2
Reputation: 27934
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.
Upvotes: 2