ASCII String to floating point
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #include <stdio.h> #include <stdbool.h> float _ASCII__String_To_Floating_Point(const char* _String); bool Is_Digit(char character); int main(void) { float Floating_Point = _ASCII__String_To_Floating_Point("123.456"); printf("%.3f\n", Floating_Point); return 0; } float _ASCII__String_To_Floating_Point(const char* _String) { float Return_Floating_Point = 0.f; char element = (char)0; while (((element = *(_String++)) != (char)0) && (Is_Digit(element))) Return_Floating_Point = Return_Floating_Point * 10.f + (element - '0'); int Exponential_Count = 0; if (element == '.') { while (((element = *(_String++)) != (char)0) && (Is_Digit(element))) { Return_Floating_Point = Return_Floating_Point * 10.f + (element - '0'); Exponential_Count--; } } if (element == 'e' || element == 'E') { int sign = 1; element = *_String++; if (element == '+') element = *_String++; else if (element == '-') { element = *_String++; sign = -1; } int index = 0; while (Is_Digit(element)) { index = index * 10 + (element - '0'); element = *(_String++); } Exponential_Count += index * sign; } while (Exponential_Count > 0) { Return_Floating_Point *= 10.f; Exponential_Count--; } while (Exponential_Count < 0) { Return_Floating_Point /= 10.f; Exponential_Count++; } return Return_Floating_Point; } bool Is_Digit(char character) { return (character >= (char)48 && character <= (char)57) ? true : false; // 48 = '0', 57 = '9' } | cs |
0 개의 댓글:
댓글 쓰기