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
| #include <stdio.h>
#include <math.h>
#define NB_ELEMS(a) ( sizeof (a) / sizeof *(a) )
static int decompose_double(double val, int int_part[], size_t taille_ip,
int dec_part[], size_t taille_dp, size_t precision);
static size_t decompose_int(int val, int tab_out[], size_t taille);
static void afficher(int tab[], size_t taille);
int main(void)
{
int intp[10] = {0};
int decp[10] = {0};
size_t precision = 5;
if (decompose_double(3.1416, intp, NB_ELEMS(intp), decp, NB_ELEMS(decp), precision) == 0)
{
afficher(intp, NB_ELEMS(intp));
printf(".");
afficher(decp, NB_ELEMS(decp));
printf("\n");
}
return 0;
}
static int
decompose_double(double val, int int_part[], size_t taille_ip, int dec_part[],
size_t taille_dp, size_t precision)
{
int err = 0;
if (taille_ip > 0 && taille_dp > 0 && taille_dp > precision)
{
int integer_part = (int) val;
int decimal_part = (int) ((val - floor(val)) * pow(10, precision));
if (decompose_int(decimal_part, dec_part, precision + 1) != 0 ||
decompose_int(integer_part, int_part, taille_ip) != 0)
{
err = 2;
}
}
else
{
err = 1;
}
return err;
}
static size_t
decompose_int(int val, int tab_out[], size_t taille)
{
size_t err = 0;
size_t n_digits = 1;
int n = val;
if (val < 0)
{
val = -val;
}
while (n > 10)
{
n_digits++;
n = n / 10;
}
if (n_digits < taille)
{
n = val;
tab_out[n_digits] = -1;
while (n_digits > 0 && n > 0)
{
tab_out[--n_digits] = n % 10;
n = n / 10;
}
}
else
{
err = 1;
}
return err;
}
static void
afficher(int tab[], size_t taille)
{
if (tab != NULL)
{
size_t i;
for (i = 0; i < taille && tab[i] != -1; ++i)
{
printf("%d", tab[i]);
}
fflush(stdout);
}
} |