0

i'm trying to create a matrix 20X20 double type so i could perform operations on it.

The problem is that when I try to print it so it could like like a matrix, there are many zeros because of the type double. And it doesn't look like a matrix.

This is what I wrote:

for (i = 0; i < SIZE; i++)
{
    for (j = 0; j < SIZE; j++)
    {   
        mat[i][j] = (rand() % (SIZE + 1) + 0);
    }       
}
for (i = 0; i < SIZE; i++)
{
    for (j = 0; j < SIZE; j++)
        printf("%10lf", mat[i][j]);
    printf("\n\n");
}

How can I make it look like 20X20 matrix and keep the double type?

Pavlin
  • 5,390
  • 6
  • 38
  • 51
Rtucan
  • 157
  • 1
  • 11

1 Answers1

2

If no precision is specified for %f argument of printf, it is using 6 decimal digits.

Also, for printf there is no need to use %lf, float arguments are always promoted to double when passed (Why does printf() promote a float to a double?). But usually, a printf implementation will ignore the l prefix.

For a proper print alignment, in this case you can use:

printf("%4.1f ", mat[i][j]);
// Here a space is added after printing the number.
// "%5.1f" could also be used for alignment (difference: the space will be prefixed),
// but then if the number will have 3 or more integer digits, it will be displayed
// "concatenated" with the previous one. Using a space prevents this

Using this, there will be 4 positions allocated to print each number, from which one position will be used by the decimal point, and another one for the decimal places (1 in this case). Two positions are remaining for the integer part (if it doesn't fit in these 2 positions, more will be used and may broke the alignment.

If running in a default Windows terminal: Even if using this alignment, there will not be enough room to print a matrix row on a single line, and 2 lines will be used. This is because by default, Windows terminal line width is 80 characters. Increasing it to 100 or more will fix the problem. This can be changed using the Properties options, or even programatically, as described here: How can I change the width of a Windows console window?

Community
  • 1
  • 1
nnn
  • 3,980
  • 1
  • 13
  • 17