C++程式:將double型別變數轉換為int型別
在C++中,int型別的變數只能儲存正整數或負整數,不能儲存小數。為此,提供了float和double型別。為了儲存小數點後最多七位的小數,建立了double資料型別。整數到double資料型別的轉換可以透過編譯器自動完成(稱為“隱式”轉換)或由程式設計師顯式請求編譯器完成(稱為“顯式”轉換)。在接下來的部分中,我們將介紹各種轉換方法。
隱式轉換
編譯器會自動進行隱式型別轉換。為此需要兩個變數:一個float型別,另一個整數型別。當我們將float值或變數簡單地賦給整數變數時,編譯器會處理其他所有事情。這種轉換存在資料丟失的問題,因為整數變數不能包含小數點後的分數部分。
語法
double input = <double value>; int output = input;
演算法
- 將double值作為輸入;
- 將該值賦給一個整數變數。
- 顯示輸出。
示例
#include <iostream> using namespace std; int solve(double value) { int opVal = value; return opVal; } int main() { double ip = 25.3056; int op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }
輸出
The input value is: 25.3056 The output value is: 25
正如我們所看到的,轉換過程相當簡單。我們只需將輸入變數賦給輸出變數;不需要額外的步驟。此外,需要注意的是,輸出中缺少double值的小數部分。
顯式轉換
當程式設計師顯式指示編譯器將一種資料型別轉換為另一種資料型別時,這稱為顯式轉換或顯式型別轉換。有兩種方法可以實現這一點:一種是在賦值時顯式宣告資料型別,另一種是使用static_cast。我們先討論第一種方法。
演算法
- 將double值作為輸入;
- 使用顯式型別轉換將值賦給整數變數。
- 顯示輸出。
賦值時指定資料型別
可以執行兩種不同的方式。一種是C風格的版本,另一種是函式風格的轉換。
C風格版本
結果資料型別在源變數之前指定,並用括號括起來。
語法
double input = <double value>; int output = (int) input;
示例
#include <iostream> using namespace std; int solve(double value) { int opVal = (int)value; return opVal; } int main() { double ip = 84.4439; int op = solve(ip); cout<< "The value before conversion: " << ip << endl; cout<< "The value after conversion: " << op << endl; return 0; }
輸出
The value before conversion: 84.4439 The value after conversion: 84
函式風格轉換
在向函式提供引數時,我們宣告結果資料型別,並將源值用括號括起來。
語法
double input = <double value>; int output = int(input);
示例
#include <iostream> using namespace std; int solve(double value) { int opVal = int(value); return opVal; } int main() { double ip = -993.6571; int op = solve(ip); cout<< "The value before conversion: " << ip << endl; cout<< "The value after conversion: " << op << endl; return 0; }
輸出
The value before conversion: -993.657 The value after conversion: -993
使用static_cast
static_cast用於在預定義型別之間進行轉換。此外,此轉換也可稱為顯式轉換,負責強制執行隱式型別轉換。
語法
double input = < double value>; int output = static_cast<int>(input);
示例
#include <iostream> using namespace std; int solve(double value) { int opVal = static_cast<int>(value); return opVal; } int main() { double ip = -65.2354; int op = solve(ip); cout<< "The value before conversion: " << ip << endl; cout<< "The value after conversion: " << op << endl; return 0; }
輸出
The value before conversion: -65.2354 The value after conversion: -65
結論
從double到整數資料型別的轉換總是會導致資料丟失,因為整數變數不能包含double變數的小數部分。當我們需要將值四捨五入到其下限值(給定分數的最小整數)時,這些轉換很有用。
廣告