string to float conversion?

前端 未结 9 1838
-上瘾入骨i
-上瘾入骨i 2020-12-18 14:16

I\'m wondering what sort of algorithm could be used to take something like \"4.72\" into a float data type, equal to

float x = 4.72;
9条回答
  •  Happy的楠姐
    2020-12-18 14:50

    As you've asked for an algorithm, not a method, here is my explanation for a simple algorithm (and an implementation in C):

    1. Initialize 4 integer variables, one for the value before dot, one for the after part, one for the power of the mantissa, one for the sign. Let's say, f, m, d, sign = 1.
    2. First look for + or - sign at the beginning. If there are no sign characters or + sign then continue. If the first character is -, then sign = -1.
    3. Then, read an integer value into f until a . or NULL character.
    4. If you end up with a dot character, then start reading the mantissa part as in the previous step into m. But this time also multiply d by 10 with each digit.
    5. In the end, return sign*(f + (float) m/d). The casting makes sure the division is done in floating-points and the type of the expression is float.

    I guess, reading the code might be easier. So here is the code:

    float atof(char *s)
    {
        int f, m, sign, d=1;
        f = m = 0;
    
        sign = (s[0] == '-') ? -1 : 1;
        if (s[0] == '-' || s[0] == '+') s++;
    
        for (; *s != '.' && *s; s++) {
                f = (*s-'0') + f*10;
        }
        if (*s == '.')
                for (++s; *s; s++) {
                        m = (*s-'0') + m*10;
                        d *= 10;
                }
        return sign*(f + (float)m/d);
    }
    

提交回复
热议问题