简体   繁体   中英

C++ multidimensional double array not working as intended

As a C# developer now trying to learn C++ i have run into an issue using multi-dimensional arrays.

The problem is that i want to fill a double[][] with any value and later print it.

This is my output:

Double
0 0 0 0 0
10 0 0 0 0 
10 0 0 0 0 
10 0 0 0 0 
10 0 0 0 0 

Int
0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 
0 1 2 3 4 

What i want is the Double output to be similar to the int one. Or to get an explanation on why the behaviour is different for the two and how to solve it.

#include <stdio.h>
#include "timer.h"


#define n 5

double A[n][n];
int B[n][n];

int main()
{
int i,j;

for (i=0; i<n; ++i)
    {
    for (j=0; j<n; ++j)
    {
        A[i][j] = (double)j;
        B[i][j] = j;
    }
    }


//Print Double array
for (i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d ",A[i][j]);
        }
        printf("\n");
    }

    printf("\n\n");

    //Print Int array
    for (i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            printf("%d ",B[i][j]);
        }
        printf("\n");
    }

return 0;
}

The answer is in how you call printf . The conversion specifier %d expects an integer argument. You are giving it a double argument, which is undefined behavior.

To achieve the correct behavior, use %f in your loop over the double array.

An aside: Your code really is C and not C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM