Search code examples
arrayscprintfdouble

Outputing a double array, unexpected output numbers in C


I tried printing an array in C, but the Output doesn't match the numbers in the array. Im just starting to learn C so this is probably a really nooby mistake but I would appreciate a solution.

int main() {
double arr[] = {1,0.2,
                0.3,0.4,0.5,
                0.6,0.7};
for(int i =0; i<7;i++){
    printf("%d ",arr[i]);
}return 0;}

Output: 0 -1717986918 858993459 -1717986918 0 858993459 1717986918


Solution

  • The %d format specifier (as well as %i) is for printing an int in decimal, not a double.

    You want to use %f instead.

    printf("%f ",arr[i]);
    

    Output:

    1.000000 0.200000 0.300000 0.400000 0.500000 0.600000 0.700000