Programming in C

(Barry) #1
Working with Arithmetic Expressions 37

int i1, i2 = -150;
char c = 'a';

i1 = f1; // floating to integer conversion
printf ("%f assigned to an int produces %i\n", f1, i1);

f1 = i2; // integer to floating conversion
printf ("%i assigned to a float produces %f\n", i2, f1);

f1 = i2 / 100; // integer divided by integer
printf ("%i divided by 100 produces %f\n", i2, f1);

f2 = i2 / 100.0; // integer divided by a float
printf ("%i divided by 100.0 produces %f\n", i2, f2);

f2 = (float) i2 / 100; // type cast operator
printf ("(float) %i divided by 100 produces %f\n", i2, f2);

return 0;
}


Program 4.5 Output


123.125000 assigned to an int produces 123
-150 assigned to a float produces -150.000000
-150 divided by 100 produces -1.000000
-150 divided by 100.0 produces -1.500000
(float) -150 divided by 100 produces -1.500000


Whenever a floating-point value is assigned to an integer variable in C, the decimal
portion of the number gets truncated. So, when the value of f1is assigned to i1in the
previous program, the number 123.125 is truncated, which means that only its integer
portion, or 123, is stored in i1.The first line of the program’s output verifies that this is
the case.
Assigning an integer variable to a floating variable does not cause any change in the
value of the number; the value is simply converted by the system and stored in the float-
ing variable.The second line of the program’s output verifies that the value of i2(–150)
was correctly converted and stored in the floatvariable f1.
The next two lines of the program’s output illustrate two points that must be remem-
bered when forming arithmetic expressions.The first has to do with integer arithmetic,
which was previously discussed in this chapter.Whenever two operands in an expression
are integers (and this applies to short,unsigned,long,and long longintegers as well),
the operation is carried out under the rules of integer arithmetic.Therefore, any decimal


Program 4.5 Continued

Free download pdf