08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2 ■ C – The Basics

6 says to print 245.8 in 6 columns; since only 5 columns are needed for printing the number,

one space is added at the beginning to make up 6 columns, so the number is printed as ◊245.8 (◊

denotes a space).

Similarly,

printf("%6.0f \n", b);

will print b as ◊◊◊246 (rounded to 0 decimal places and printed in a field width of 6).

If the specification was %3.1f and the value to be printed is 245.8, it would be printed using

5 print columns, even though the field width is 3. Again, when the field width specified is smaller

than the number of print columns required, C ignores the field width and prints the value using

as many columns as needed.

We can sometimes use this to our advantage. If we do not know how big a value might be,

we can deliberately use a small field width to ensure it is printed using the exact number of print

columns required for printing the value.

In general, suppose the float or double value v is to be printed with the specification %w.df

where w and d are integers. Firstly, the value v is rounded to d decimal places. Suppose the

number of print columns required to print v, including a possible point (there will be no point if

d = 0; the value is to be rounded to a whole number) and a possible sign, is n. There are two cases

to consider:

1. If n is less than w (the field width is bigger), the value is padded on the

left with (w - n) spaces. For example, suppose w is 7 and the value to be

printed is -3.45 so that n is 5. The number is padded on the left with (7-

5) = 2 spaces and printed as ◊◊-3.45.

2. If n is greater than or equal to w (field width is the same or smaller), the

value is printed using n print columns. In this case, the field width is

ignored.

As with integers, a field width is useful when we want to line up numbers one below the

other. Assume we have three double variables a, b, and c with values 419.563, -8.7, and 3.25,

respectively. Suppose we want to print the values to two decimal places, lined up on the decimal

point, like this:

419.56

-8.70

3.25

Since the biggest number requires 6 print columns, we can line them up using a field width of

at least 6. The following statements will line them up as above:

printf("%6.2f \n", a);

printf("%6.2f \n", b);

printf("%6.2f \n", c);

35

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!