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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <inttypes.h>
long double string_to_long_double(char *input) ;
int main(int argc, char *argv[]) {
if (argc != 2 || strcmp(argv[1],"-h") == 0 ) {
fprintf(stdout,"usage: %s float_value\n",argv[0]) ;
exit(EXIT_FAILURE) ;
}
long double res ;
res=string_to_long_double(argv[1]) ;
fprintf(stdout,"Entry: %s output: %.19Lf\n",argv[1],res) ;
exit(EXIT_SUCCESS) ;
}
long double string_to_long_double(char *input) {
long double res_tmp ;
long double res_rounded ;
long double cc ;
int8_t c ;
long double fp_exp ;
char *ptr_float_point ;
_Bool is_negativ = false ;
char *integer_part_str=calloc(32,sizeof(char)) ;
char *float_part_str=calloc(32,sizeof(char)) ;
char *res_string=calloc(32,sizeof(char)) ;
if (input[0] == '-') {
input++ ;
is_negativ=true ;
}
strcpy(integer_part_str,input) ;
ptr_float_point=strchr(input,'.') ;
integer_part_str[ptr_float_point-input]='\0' ; /** Get only integer part of the float */
res_tmp = 0.0 ;
strcpy(float_part_str,input) ;
for (c=(int) strlen(integer_part_str)-1, cc=1 ; c >= 0 ; c--,cc *= 10) {
res_tmp += ((int) (integer_part_str[c] - 48) * cc) ; /** Increment integer part */
float_part_str++ ; /** for getting an pointer only on the float part. */
if (c == 0) {
float_part_str++ ; /** for getting an pointer only on the float part. */
break ;
}
}
for (c=0, fp_exp=0.1; c < (int) strlen(float_part_str) ; c++, fp_exp /= 10.0 ) {
char *exponent_str=calloc(32,sizeof(char)) ;
fprintf(stdout,"float multiplicator not cleaned -> %.19Lf\n",fp_exp) ;
/** Clean fp_exp value method */
sprintf(exponent_str,"%.*Lf",c+1,fp_exp) ;
sscanf(exponent_str,"%Lf",&fp_exp) ;
res_tmp += ((int) (float_part_str[c] - 48) * fp_exp) ; /** Increment float part */
fprintf(stdout,"float multiplicator cleaned -> %.19Lf\n",fp_exp) ;
free(exponent_str) ;
}
/** Final result with the right rounding as the given string */
sprintf(res_string,"%.*Lf",(int) strlen(float_part_str),res_tmp) ;
sscanf(res_string,"%Lf",&res_rounded) ;
for (c=(int) strlen(integer_part_str)-1 ; c >= 0 ; c--) {
/** Reset the right address for freeing pointer */
float_part_str-- ;
if (c == 0) {
float_part_str-- ;
break ;
}
}
free(integer_part_str) ;
free(float_part_str) ;
free(res_string) ;
if (is_negativ) {
res_rounded = -res_rounded ;
input-- ;
}
fprintf(stdout,"Result -> %.19Lf\n",res_rounded) ;
return res_rounded ; /** But the returned value is dirty too... */
} |
Partager