问题
I want to write a program in C++ to cin a Decimal number and cout the digits after Decimal for example 0.26547 -> 5.
I wrote this but not work correctly:
int main()
{
int i=0,b;
float a ;
cin>>a ;
while(a!=0)
{
a*=10 ;
b=a ;
a-=b ;
i+=1 ;
}
cout<<i ;
}
For example for 0.258 instead of 3, returns 20. can one explain me what is the problem of this code ? thank you
回答1:
C++ permits decimal representation of floating point numbers, but as far as I know all extant implementations use binary representation. And then the idea of storing the user's decimal number specification as a floating point value, loses critical information about the decimal digits: they're simply not there any more. So to count the decimal digits in the specification, you have to store it as a string.
Pseudo-code:
- input number specification as a string, e.g. using
getline
. - verify that it's a valid number specification, e.g. using
stod
. - scan for the first period from the right, call this position P.
- scan for the maximum number of decimal digits from position P.
回答2:
I am unsure why your code does not work (What compiler are you using?), but I think it might related to
b=a;
Try explicitly casting your float to an int
b = int(a);
Alternatively, you could choose not to use an int, and round a float down using the function floor
by including math.h #include <math.h>
float a = 5.9f;
float b = floor(a);
a -= b;
来源:https://stackoverflow.com/questions/41197139/how-to-find-digits-after-decimal