counting float digits (hw) C

不羁的心 提交于 2020-03-05 08:29:49

问题


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?

  1. Read characters with getchar until you hit whitespace/enter/end of input
  2. Collect them all into a single string
  3. Use strtod to make sure it's a valid floating point value
  4. Count digits in the string - either before, or after the point, whatever you need.

If you're limited to only getchar:

  1. Read chars one by one with getchar
  2. Keep a state of where you are in the number: before decimal point, at decimal point, or after
  3. 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)
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!