C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
FIGURE 4.1 printf() conversion characters determine how and where numbers print.

Strings and characters have their own conversion characters as well. Although you don’t need %s to
print strings by themselves, you might need %s when printing strings combined with other data. The
next printf() prints a different type of data value using each of the conversion characters:


Click here to view code image


printf("%s %d %f %c\n", "Sam", 14, -8.76, 'X');

This printf() produces this output:


Sam 14 -8.760000 X

Note

The string Sam needs quotation marks, as do all strings, and the character X needs
single quotation marks, as do all characters.

Warning

C is strangely specific when it comes to floating-point numbers. Even though the -
8.76 has only two decimal places, C insists on printing six decimal places.

You can control how C prints floating-point values by placing a period (.) and a number between the
% and the f of the floating-point conversion character. The number you place determines the number
of decimal places your floating-point number prints to. The following printf() produces four
different-looking numbers, even though the same floating-point number is given:


Click here to view code image


printf("%f %.3f %.2f %.1f", 4.5678, 4.5678, 4.5678, 4.5678);

C rounds the floating-point numbers to the number of decimal places specified in the %.f conversion
character and produces this output:


4.567800 4.568 4.57 4.6

Tip

You probably don’t see the value of the conversion characters at this point and think
that you can just include the information in the controlString. However, the
conversion characters will mean a lot more when you learn about variables in the next
chapter.
Free download pdf