问题
I need to count digits from a float
number and keep the number.
I can use scanf()
with %f
or %c
but not %s
, and I can use getchar()
.
I can use getchar but I will loose the number.
回答1:
Why will you lose the number with getchar
?
- Read characters with getchar until you hit whitespace/enter/end of input
- Collect them all into a single string
- Use
strtod
to make sure it's a valid floating point value - Count digits in the string - either before, or after the point, whatever you need.
If you're limited to only getchar
:
- Read chars one by one with
getchar
- Keep a state of where you are in the number: before decimal point, at decimal point, or after
- Keep counting the digits as long as it's a valid floating point number (i.e. 1 or more digits, then optionally a decimal point with 1 or more digits after it)
- Collect the digits into a floating point number by shifting powers of 10 (i.e. before decimal point multiply by 10.0 and add new number, after decimal point divide by a growing power of 10 and add).
回答2:
As I see you got your answer, but is this works for you too ?
#include <stdio.h>
int main()
{
char *str = new char[30];
float flt;
int count = 0;
scanf( "%f", &flt);
printf( "number you entered is: %f\n", flt);
sprintf(str, "%f", flt );
for( ;str[count] != '\0'; count++ );
printf( "%f have %d digits", flt, count-1);
return 0;
}
来源:https://stackoverflow.com/questions/1988160/counting-float-digits-hw-c