// Printf.cc - shows examples of using printf #include using namespace std; int main() { double a = 123456789 ; double b = -a/1e6 ; double c = -b/1e6 ; double d = -c/1e6 ; cout << "NICE FORMATTING EXAMPLES\n" ; cout << " Integers left aligned, right-aligned and zero-filled in a fixed-width space" << endl ; for ( int i = -14 ; i <= 140 ; i += 7 ) { printf( "| %-3d | %3d | %04d |\n" , i , i , i ) ; } cout << endl << "UGLY FORMATTING EXAMPLES\n" ; printf( "\n Doubles formatted in the default general way (%%g) \n" ) ; printf( "%g %g %g %g\n" , a,b,c,d ) ; printf( "\n The same Doubles formatted in the default floating point way (%%f) \n" ) ; printf( "%f %f %f %f\n" , a,b,c,d ) ; printf( "\n Doubles formatted in 8 columns with 3 decimal places (%%8.3f); first right aligned then left \n" ) ; printf( "%8.3f %8.3f %8.3f %8.3f\n" , a,b,c,d ) ; printf( "%-8.3f %-8.3f %-8.3f %-8.3f\n" , a,b,c,d ) ; cout << " (The '8' is a suggestion, not a demand. If a number doesn't fit \n\ in 8 columns then more are used)\n\n" ; cout << "NICE FORMATTING EXAMPLES\n" ; printf( "\n Doubles formatted in 8 columns with 2 decimals (%%8.2g); first left aligned, then right \n" ) ; printf( "%-8.2g %-8.2g %-8.2g %-8.2g\n" , a,b,c,d ) ; printf( "%8.2g %8.2g %8.2g %8.2g\n" , a,b,c,d ) ; printf( "\n Doubles formatted in 10 columns with 2 decimals (%%10.2g); first left aligned, then right \n" ) ; printf( "%-10.2g %-10.2g %-10.2g %-10.2g\n" , a,b,c,d ) ; printf( "%10.2g %10.2g %10.2g %10.2g\n" , a,b,c,d ) ; char r[]= "|...10...| " ; printf( "%s%s%s%s\n" , r,r,r,r ) ; printf( "\n Doubles formatted in 11 columns with 5 decimals (%%11.5g); first left aligned, then right \n" ) ; printf( "%-11.5g %-11.5g %-11.5g %-11.5g\n" , a,b,c,d ) ; printf( "%11.5g %11.5g %11.5g %11.5g\n" , a,b,c,d ) ; char ro[]= "|...11....| " ; printf( "%s%s%s%s\n" , ro,ro,ro,ro ) ; printf( "\n Doubles formatted in 15 columns with 9 decimals (%%15.9g); first left aligned, then right \n" ) ; printf( "%-15.9g %-15.9g %-15.9g %-15.9g\n" , a,b,c,d ) ; printf( "%15.9g %15.9g %15.9g %15.9g\n" , a,b,c,d ) ; char row[]= "|.....15......| " ; printf( "%s%s%s%s\n\n" , row,row,row,row ) ; }