Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Comes After The %?

Tags:

c

I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using printf?. For example:

double radius = 1.0;
double area = 0.0;
area = calculateArea( radius );
printf( "%10.1f     %10.2\n", radius, area );

I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with 10.1f and 10.2f? Could someone please explain this?

like image 908
The.Anti.9 Avatar asked Aug 20 '08 13:08

The.Anti.9


3 Answers

http://en.wikipedia.org/wiki/Printf#printf_format_placeholders is Wikipedia's reference for format placeholders in printf. http://www.cplusplus.com/reference/clibrary/cstdio/printf.html is also helpful

Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc).

Hope this helps

UPDATE:

To clarify using your examples:

printf( "%10.1f     %10.2\n", radius, area );

%10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place.

%10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.

like image 58
robintw Avatar answered Sep 30 '22 16:09

robintw


man 3 printf

on a Linux system will give you all the information you need. You can also find these manual pages online, for example at http://linux.die.net/man/3/printf

like image 26
Eli Courtwright Avatar answered Sep 30 '22 17:09

Eli Courtwright


10.1f means floating point with 1 place after the decimal point and the 10 places before the decimal point. If the number has less than 10 digits, it's padded with spaces. 10.2f is the same, but with 2 places after the decimal point.

On every system I've seen, from Unix to Rails Migrations, this is not the case. @robintw expresses it best:

Basically in a simple form it's %[width].[precision][type].

That is, not "10 places before the decimal point," but "10 places, both before and after, and including the decimal point."

like image 33
James A. Rosen Avatar answered Sep 30 '22 15:09

James A. Rosen