08.01.2023 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2 ■ C – The Basics

2.6.5 Assigning double/float to int

Consider:

double d = 987.654321;

int n = d;

printf("%d \n", n);

The value 987 is printed. When we assign a floating-point value to an int, the fractional

part, if any, is dropped (not rounded) and the resulting integer value is assigned. It is up to us

to ensure that the integer obtained is small enough to fit in an int. If not, the resulting value is

unpredictable.

On one compiler, where the largest value of an int was 32767, when d was changed to

987654.321, the value printed was 4614, a far cry from what might be expected, seemingly

unpredictable. (Not quite unpredictable; the value assigned is 987654 % 32768, which is 4614.

In general, if big represents a value that is too big to be stored, the value actually stored is big %

32768 for integers stored in 16 bits.) This is because the truncated value of d is 987654, which is

too big to fit in an int variable. As an exercise, see what value would be printed on your compiler.

If we want the rounded value of d stored in n, we could do this with

n = d + 0.5;

If the first digit after the point in d is 5 or more, adding 0.5 would add 1 to the whole number

part. If the first digit after the point is less than 5, adding 0.5 would not change the whole number

part.

For example, if d is 245.75, adding 0.5 would give 246.25 and 246 would be assigned to n.

But if d were 245.49, adding 0.5 would give 245.99 and 245 would be assigned to n.

2.7 Strings

So far, we have seen several examples of string constants in printf statements.

A string constant is any sequence of characters enclosed in double quotes. Examples are:

"Once upon a time"

"645-2001"

"Are you OK?"

"c:\\data\\castle.in"

The opening and closing quotes must appear on the same line. In other words, C does not

allow a string constant to continue on to another line. However, a long string can be broken up

into pieces, with each piece on one line. When the program is compiled, C will join the pieces,

making one string. For example,

printf("Place part of a long string on one line and "

"place the next part on the next line. The parts are "

"separated by whitespace, not comma or ; \n");

38

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!