C++程式將int變數轉換為double


C++中的Int型別變數用於儲存正數或負整數,但此型別無法儲存小數。為此,存在float和double值。Double資料型別專門設計用於儲存小數點後最多七位的小數。整數和double變數之間的轉換可以由編譯器自動處理,稱為“隱式”轉換,也可以由程式設計師顯式觸發到編譯器。我們將在以下部分討論不同的轉換方式。

隱式轉換

隱式型別轉換由編譯器自動完成。為此,我們取兩個變數;一個為整數型別,另一個為浮點型別。然後,我們只需將整數值或變數賦給浮點變數,其餘所有操作都將由編譯器處理。

演算法

  • 將整數值作為輸入。
  • 將該值賦給double變數。
  • 顯示輸出。

語法

int input = <integer value>;
double output = input;

示例

#include <iostream> using namespace std; double solve(int value) { double opVal = value; return opVal; } int main() { int ip = 25; double op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

輸出

The input value is: 25
The output value is: 25

我們可以看到轉換過程非常簡單。我們不需要執行任何特殊操作;我們只需將輸入變數賦給輸出變數。

顯式轉換

當程式設計師專門指示編譯器將一種資料型別轉換為另一種資料型別時,就會發生顯式轉換。這可以透過兩種方式完成,一種是在賦值期間提及資料型別,另一種是使用static_cast。我們首先描述第一種方法。

演算法

  • 將整數值作為輸入;
  • 使用顯式強制轉換為布林值,將該值賦給double變數。
  • 顯示輸出。

賦值期間提及資料型別

這也可以透過兩種不同的方式完成。一種是C風格版本,另一種是函式風格轉換。

C風格版本

我們在源變數或括號內包含的值之前提及結果資料型別。

語法

int input = <integer value>;
double output = (double) input;

示例

#include <iostream> using namespace std; double solve(int value) { double opVal = (double) value; return opVal; } int main() { int ip = 35; double op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

輸出

The input value is: 35
The output value is: 35

函式風格轉換

我們像傳遞引數給函式一樣,提及結果資料型別並將源值括在括號內。

語法

int input = <integer value>;
double output = double(input);

示例

#include <iostream> using namespace std; double solve(int value) { double opVal = double(value); return opVal; } int main() { int ip = 45; double op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

輸出

The input value is: 45
The output value is: 45

使用static_cast

語法

int input = <integer value>;
double output = static_cast<double>(input);

示例

#include <iostream> using namespace std; double solve(int value) { double opVal = static_cast<double>(value); return opVal; } int main() { int ip = 55; double op = solve(ip); cout<< "The input value is: " << ip << endl; cout<< "The output value is: " << op << endl; return 0; }

輸出

The input value is: 55
The output value is: 55

從最後三個示例中,我們可以看到顯式轉換過程幾乎相同,無論我們使用static_cast、C風格轉換還是函式風格轉換。在這三種情況下,我們都必須在賦值之前提及結果資料型別。

結論

介紹了幾種將整數轉換為double值的方法。程式設計師必須確定哪種轉換方法最適合特定情況,因為不同的轉換場景需要不同的轉換方法。但是,由於隱式轉換是自動執行的,因此程式設計師不必擔心執行復雜的策略。

更新於: 2022年10月19日

11K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告