Divide decimal double


I need to decompose the decimal part of the number into single digits, but I need to get the most obvious idea. Here is my code to be clearer:

#include <stdio.h>

void main(){
    double value = 0.123;
    int decim_tab[6];
    int decimal;
    int i;

    for (i = 0; i < 6; ++i) {
        value *= 10;
        decimal = (int)value;
        decim_tab[i] = decimal;
        value -= decimal;
    }
    for (i = 0; i < 6; ++i)
        print("%d\n", decim_tab[i]);
}

The result I need is:

1
2
3
0
0
0

But I get:

1
2
2
9
9
9

EDIT

The solution I found is to add a small delta to the value to force the shortest view:

#include <stdio.h>

void main(){
    double value = 0.123;
    int decim_tab[6];
    int decimal;
    int i;

    value += 0.000000001
    for (i = 0; i < 6; ++i) {
        value *= 10;
        decimal = (int)value;
        decim_tab[i] = decimal;
        value -= decimal;
    }
    for (i = 0; i < 6; ++i)
        print("%d\n", decim_tab[i]);
}

I would be happy to find a better way, any suggestions?

+4
source share
3 answers

, , , ( ) . printf("%.20f", value); value, , 0.123 0.12299..., .

, :

#include <stdio.h>
#include <stdlib.h>

int main(){
    double value = 0.123;
    char *s = malloc(9);

    sprintf(s++, "%.6f", value);
    while(*s++){
        putchar(*s);
        putchar('\n');
    }
}

EDIT: , , , , . .

+3

6 , 0.0000005 (.. 0.5e-6), . , , .

+1

. :

double a = 0.15 + 0.15; // 0.15 + 0.15 == 0.3, right?
double b = 0.1 + 0.2;   // 0.1 + 0.2 == 0.3, right?
if (a == b) {
  printf("Equal\n");
} else {
  printf("Unequal\n");
}

? Equal? ? :

http://rextester.com/VZOZ1043

It prints Unequalbecause there are some numbers that a floating point cannot represent exactly and what you always need to keep in mind when doing floating point math. There is also rounding involved in many operations, so the results of mathematical operations are as possible as possible, but not always "accurate", there is a tiny error that can also be added if you perform several operations.

double value = 0.123;

// Assuming none of your numbers has more than 58 digits,
// one period and one termination char.
char buffer[60];

// Print the number to the buffer.
// Missing: Error checking if it did fit!
snprintf(buffer, sizeof(buffer), "%f", value);

// Find the period or end of string
int idx = 0;
for (; buffer[idx] && buffer[idx] != '.'; idx++);

// Print anything after the period till 
// the end of the string
if (buffer[idx] == '.') {
    for (idx++; buffer[idx]; idx++) {
        printf("%c\n", buffer[idx]);
    }
}

Check this out: http://rextester.com/CYDQO24769

+1
source

Source: https://habr.com/ru/post/1660276/


All Articles