/* Some examples about mathematical expressions and casting */ #include int main() { int x = 2; int y = 3; float z = 3; float result; /* Division between integer numbers, the result is the integer number 0, then converted in the float number 0.000000 for the assignment to the variable result */ result = 2/3; printf("A: %f\n", result); /* Division between an integer and a float number, the integer number is converted in a float number, and the operation is perform between two floats. The result is 0.666667. */ result = 2.0/3; printf("B: %f\n", result); /* The same as the last operation. The number 3. is considered a float number */ result = 2/3.; printf("C: %f\n", result); /* Division between integer variable, the result is the integer number 0, then converted in the float number 0.000000 for then assignment */ result = x/y; printf("D: %f\n", result); /* The casting operator (float) converts the content of the variable x in a float number. Since now the division is performed between a float and an integer number, the integer number is converted in a float number, and the operation is perform between two floats. The result is 0.666667. */ result = (float)x/y; printf("E: %f\n", result); /* As before, in a division between an integer and a float value, the integer value is converted in a float and the division is performed between two floats. */ result = x/z; printf("F: %f\n", result); /* The division x/y is a division between integer numbers (result is 0), the value 0 is then converted in a float value (0.000000), and then it is multiplied by x (which is converted into a float number because the other operator (float)(x/y) is a float number). The final result is 0.000000 */ result = (float)(x/y) * x; printf("G: %f\n", result); /* In this case, the content of the variable x inside brackets is converted in a float number, for this reason the division is performed between float numbers, obtaining a float result. The result of the division is multiplied with x and, once again, the operation is performed between float numbers because one operand is a float. The result is 1.333333. */ result = ((float)x/y) * x; printf("H: %f\n", result); /* In this last case, the result of the operation between the outer brackets is 1.333333 as in the previous operation (H:). This number is then converted in a int value and then saved in the result variable that is of type float. As a consequence, the content of the variable result is 1.000000. */ result = (int) ( ((float)x/y) * x ); printf("I: %f\n", result); return 0; }