Using precision while printing integers, floating-point numbers and strings using printf() C function
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)
Other info: none
To do: Using precision while printing integers, floating-point numbers and strings using printf() C function
To show: How to use precision while printing integers, floating-point numbers and strings using printf() C function
// Using precision while printing integers, floating-point numbers and strings
#include <stdio.h>
int main(void)
{
int i = 873;
float f = 123.94536;
// Unsized array
char s[] = "Happy Birthday";
printf("Using precision while printing integers,\n");
printf(" floating-point numbers, and strings.\n");
printf("Compare the output with the source code\n");
printf("----------------------------------------\n\n");
printf("Using precision for integers\n");
printf("\t%.4d\n\t%.9d\n\n", i, i);
printf("Using precision for floating-point numbers\n");
printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f);
printf("Using precision for strings\n");
printf("\t%.11s\n", s);
return 0;
}
Output example:
Using precision while printing integers,
floating-point numbers, and strings.
Compare the output with the source code
----------------------------------------
Using precision for integers
0873
000000873
Using precision for floating-point numbers
123.945
1.239e+002
124
Using precision for strings
Happy Birth
Press any key to continue . . .