【問題】type coercion and type casting


Recommended Posts

type coercion

Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler.

double  d;
long l;
int i;

if (d > i) d = i;
if (i > l) l = i;
if (d == l) d *= 2;

type casting

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).

double da = 5.5;
double db = 5.5;
int result = (int)da + (int)db;
//Result would be equal to 10 instead of 11.

說白話就是一個編譯器會幫你自動轉換資料型態...

另外一個是你自己強制轉換...

P.S.:剛剛在找這兩個東西的資料的時候一直google到這一篇主題XDDDDDD

此內容已被編輯, ,由 j100002ben
鏈接文章
分享到其他網站
那type coercion的意是就是

d可以從double變成int或long???

type coercion的意思是說~~

編譯器會用他自己的邏輯去判斷需要作資料型態轉換的部份

像是如果

a = 1

if(a)會是true

a = 100

if(a)還是true

雖然 bool型態和int型態是不一樣的

不過他們可以再這邊使用的原因就是因為編譯器和你處理掉了..

另外一個例子是C語言的char 和short int

他們也是可以互相轉換的~~

再來看看錢一個回覆的例子


double da = 5.5;
double db = 5.5;

如果是type coercion

int result = da + db;
// =5.5+5.5 = 11

不過如果使用強制cast轉換

int result = (int)da + (int)db;
// = 5 + 5 = 10

此內容已被編輯, ,由 j100002ben
鏈接文章
分享到其他網站
訪客
這個主題現在已關閉,不能再回覆。