string to float conversion?

前端 未结 9 1833
-上瘾入骨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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 14:54

    I assume you want an actual algorithm, not a library function that already does it. I don't have time to write and test actual code, but here is what I would do:

    1. Initialize a float that will be used as an accumulator to 0.
    2. Figure out where the decimal place is in the string, this will let you know what "column" each of the digits is (i.e. 100s, 10s, 1s, 1/10ths, etc).
    3. Start at the beginning of the string.
    4. Take that digit, convert to an int (trivially done by subtracting 0x30 from the ASCII value)
    5. Multiply the value by the place column (for the first digit in your example, that would be 4 * 1 == 4, for the next digit 7 * 0.1 == 0.7).
    6. Add the result to the accumulator
    7. Repeat from step 4 for each remaining digit.
    8. The accumulator now contains your result.

    Due to the roundoff of converting between base 10 and base 2 in every iteration of this loop, the result you get from this algorithm may not be the closest possible binary representation to the original value. I don't really know of a good way to improve it though... perhaps someone else can chime in with that.

提交回复
热议问题