简体   繁体   中英

C - (Printf) Forcing Display of Zeros

I've got:

void pprint_matrix(matrix *m)
{
    int n,k,p;
    matrix* row = new_matrix(1,m->j);

    for (k = 1; k < (m->i)+1; k++)
    {
        p = 0;
        for (n = (m->j)*k-(m->j); n < (m->j)*k; n++)
        {
            row->m[p] = m->m[n];
            p++;
        }
        for (n = 0; n < m->j; n++)
        {
            printf("(%+#3.3g%+#3.3gi)  ",row->m[n].re,row->m[n].im);
        }
        printf("\n");
    }
}

Which is printing:

(-1.73+0.00i)  (+0.866+0.00i)  (-0.722+0.00i)  (-0.866+0.00i)  
(+0.00+0.00i)  (-0.707+0.00i)  (+0.707+0.00i)  (+0.707+0.00i)  
(+0.00+0.00i)  (+0.00+0.00i)  (+0.204+0.00i)  (+0.00+0.00i) 

another example of print output:

(-2.24+0.00i)  (+2.22e-16+0.00i)  (-1.12+0.00i)  (-1.79+0.00i)  
(+0.00+0.00i)  (+1.58+0.00i)  (+0.00+0.00i)  (+0.632+0.00i)  
(+0.00+0.00i)  (+5.55e-17+0.00i)  (-0.725+0.00i)  (-1.04+0.00i)  
(+0.00+0.00i)  (+2.22e-16+0.00i)  (-0.589+0.00i)  (-0.816+0.00i)  
(+0.00+0.00i)  (+2.22e-16+0.00i)  (+0.0467+0.00i)  (+0.404+0.00i)  

I want to get rid of that offset. How can I force this alignment given the preceding code? The function I've listed really isn't important to the question. It's just a question about printf.

For clarity, the goal is something like this:

(  ) (  ) (  )
(  ) (  ) (  )
(  ) (  ) (  )

use %3.3f instead of %3.3g

I assume your question is that you want your output to have constant with, such that the result forms aligned columns.

First, use %f instead of %g to get rid of the exponent notation for small numbers.

Second, increase the width. %+#3.3f asks for three digits to the right of the decimal point, plus a leading sign, and so forth, and please pad with spaces on the left if the results is shorter than three characters. If you instead use, for example, %+#7.3f you stand a better chance of getting aligned columns.

If you just want more padding to form columns, you can try:

printf("(%+#8.3g%+#8.3gi)  ",row->m[n].re,row->m[n].im);

If you want them 0 padded, just add a 0 to the format:

printf("(%+0#8.3g%+0#8.3gi)  ",row->m[n].re,row->m[n].im);

Another possibility is to use sprintf (or, preferably, snprintf ) to format each entry to a string, then print the string using %-12s , or whatever length is appropriate.

Or use %...e if you always want scientific notation (the ... is not literal).

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