简体   繁体   中英

Trouble printing 5 elements of a double array per line in C

I've been working on an assignment for school, basically we're creating 2 arrays of random doubles, then sorting them using 3 different algorithms and printing the results. The output needs to be printed with 5 elements per line.

I've got this code:

    //print sorted arrayB
for (i = 0; i < size; i++)
{
    printf ("%.1lf  ", arrayB[i]);
    if (i % 5 == 0 && i > 0)
    {
        printf ("\n");
    }
}

where all variables are defined before the sort, and my output looks like this every time:

1.0  2.0  3.0  4.0  5.0  6.0
7.0  8.0  9.0  10.0 11.0
12.0 13.0 14.0 15.0 16.0
17.0 18.0 19.0 20.0 21.0
etc...

I don't understand why it's printing 6 elements in the top row, and 5 in all the rest. Any help is greatly appreciated!

You need to update the \\n condition as below -

if ((i+1) % 5 == 0)
    {
        printf ("\n");
    }

i % 5 will cause newlines after indices 5,10,15.. . This is your case where you have 6 at index 5, 11 at index 10.. Rather you need to break at 4,9,14.. . which are all covered by (i+1) .

Just write the evaluation by hand for your conditional:

if (i % 5 == 0 && i > 0)

i  result
0  false
1  false
2  false
3  false
4  false
5  true
6  false

Now we can see that it is false 5 times, then true, which makes it print a newline, but only after you printed the number!

So you need to rearrange your logic slightly, but the conditional is correct.

The point is in the && i > 0 part of the if statement. If you'd remove it, this would be the output:

1.0
2.0  3.0  4.0  5.0  6.0
7.0  8.0  9.0  10.0 11.0
12.0 13.0 14.0 15.0 16.0
17.0 18.0 19.0 20.0 21.0
etc...

By excluding zero, you have prevented printing the newline after the first number, see?

The solution is to move the i index by one, like this:

if ((i + 1) % 5 == 0)
{
    printf ("\n");
}

Now you don't even need the && i > 0 part, because i + 1 will never be zero.

Just add 1 to i(therefore the condition i > 0, becomes unnecessary), which will solve. This occurs because in the condition imposed by you, for the first line break (\\ n) to occur, it will have to go from 0 to 5, and to do so you will have to repeat the loop 6 times, so on the first line it showed 6 numbers , instead of 5

Like this:

#include <stdio.h>
#define SIZE 25

int main() {
 int i, arrayB[SIZE] = {0};
 for (i = 0; i < SIZE; i++)
 {
     printf ("%.1lf  ", arrayB[i]);
     if ((i+1) % 5 == 0)
     {
         printf ("\n");
     }
 }
return 0;
}

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