C/Console/Formatted Output Int
Содержание
Formatted output: int, float and string
#include <stdio.h>
int main(void)
{
printf("%.5d\n", 10);
printf("$%.2f\n", 99.95);
printf("%.10s", "This is a long line\n");
return 0;
}
Integer output variations
#include <stdio.h>
void main()
{
int i = 159;
int j = 3459;
int k = 45679;
long li = 567289L;
long lj = 6789212L;
long lk = 234562789L;
printf("\ni = %d j = %d k = %d i = %6.3d j = %6.3d k = %6.3d\n",
i ,j, k, i, j, k);
printf("\ni = %-d j = %+d k = %-d i = %-6.3d j = %-6.3d k ="
" %-6.3d\n",i ,j, k, i, j, k);
printf("\nli = %d lj = %d lk = %d\n", li, lj, lk);
printf("\nli = %ld lj = %ld lk = %ld\n", li, lj, lk);
}
Output formatted ramdom integer
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i;
for( i = 0; i < 10; i++)
printf("%10d %10d %10d\n", rand(), rand(), rand());
return 0;
}
Output justify
#include <stdio.h>
int main(void)
{
printf(".........................\n");
printf("right-justified: %8d\n", 100);
printf(" left-justified: %-8d\n", 100);
return 0;
}
Print formatted data to stdout: how to use printf
#include <stdio.h>
int main()
{
printf ("Characters: %c %c \n", "a", 22);
printf ("Decimals: %d %ld\n", 1933, 330000);
printf ("Preceding with blanks: %10d \n", 1924);
printf ("Preceding with zeros: %010d \n", 1965);
printf ("Some different radixes: %d %x %o %#x %#o \n", 200, 200, 200, 200, 200);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 53, 140);
printf ("%s \n", "A line of text.");
return 0;
}
Variations on a single integer
#include <stdio.h>
void main()
{
int k = 1234;
printf("%%d %%o %%x %%X"); /* Display format as heading */
printf("\n%d %o %x %X", k, k, k, k ); /* Display values */
/* Display format as heading then display the values */
printf("\n\n%%8d %%-8d %%+8d %%08d %%-+8d");
printf("\n%8d %-8d %-+8d %08d %-+8d\n", k, k, k, k, k );
}