C-like languages
Implicit type conversion
Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some programming languages allow compilers to provide coercion; others require it.
In a mixed-type expression, data of one or more subtypes can be converted to a supertype as needed at runtime so that the program will run correctly. For example, the following is legal C language code:
double d;
long l;
int i;
if (d > i) d = i;
if (i > l) l = i;
if (d == l) d *= 2;
Although d
, l
and i
belong to different data types, they will be automatically converted to equal data types each time a comparison or assignment is executed. This behavior should be used with caution, as unintended consequences can arise. Data can be lost when converting representations from floating-point to integer, as the fractional components of the floating-point values will be truncated (rounded toward zero). Conversely, precision can be lost when converting representations from integer to floating-point, since a floating-point type may be unable to exactly represent an integer type. For example, float
might be an IEEE 754 single precision type, which cannot represent the integer 16777217 exactly, while a 32-bit integer type can. This can lead to unintuitive behavior, as demonstrated by the following code:
#include <stdio.h>
int main(void)
{
int i_value = 16777217;
float f_value = 16777216.0;
printf("The integer is: %d\n", i_value);
printf("The float is: %f\n", f_value);
printf("Their equality: %d\n", i_value == f_value);
}
On compilers that implement floats as IEEE single precision, and ints as at least 32 bits, this code will give this peculiar print-out:
The integer is: 16777217
The float is: 16777216.000000
Their equality: 1
Note that 1 represents equality in the last line above. This odd behavior is caused by an implicit conversion of i_value
to float when it is compared with f_value
. The conversion causes loss of precision, which makes the values equal before the comparison.
Important takeaways:
float
toint
causes truncation, i.e., removal of the fractional part.double
tofloat
causes rounding of digit.long
toint
causes dropping of excess higher order bits.
Explicit type conversion
Explicit type conversion is a type conversion which is explicitly defined within a program (instead of being done by a compiler for implicit type conversion). It is defined by the user in the program.
double da = 3.3;
double db = 3.3;
double dc = 3.4;
int result = (int)da + (int)db + (int)dc; //result == 9
//if implicit conversion would be used (as with "result = da + db + dc"), result would be equal to 10
Comments
在C语言中,不能使用 a == b 来判断是否相等,因为有效数位后的数字可能不相等。
在C语言中,需要采用 | a - b | < 1e-6 来判断两个数是否相等。即差足够小就可以认为两数相等。