
這樣子 operand 會被強迫轉換型態為小括弧中的 type 。
例如
#include <iostream>
int main()
{
int a = 34;
int b = 8;
double c, d;
d = a / b;
c = (double) a / b;
std::cout << d << std::endl;
std::cout << c << std::endl;
return 0;
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:cast.cpp
功能:示範 cast 運算
作者:張凱慶
時間:西元 2010 年 10 月 */編譯後執行,結果如下

第 9 行
d = a / b;
雖然變數 d 被宣告為 double 型態,但由於 a 與 b 都是整數 int 型態,所以這裡會是整數除法 (integer division) ,也就是會得到整數的結果,小數點以下會省去。
第 10 行
c = (double) a / b;
運用 cast 運算子將 a 除以 b 的結果強制轉換成 double 型態,因此變數 c 可以得到正確的結果。
| 中英文術語對照 | |
|---|---|
| 強迫轉型 | explicit conversion |
| 整數除法 | integer division |
您可以繼續參考
運算式
型態轉換
相關目錄
回 C++ 快速導覽
回 C++ 教材
回首頁
參考資料
C++ reference
cplusplus.com
Cprogramming.com C++ Tutorial
C++ Primer, Fourth Edition, Stanley B. Lippman...
本文於 2013 年 1 月更新
沒有留言:
張貼留言