2013-10-21 276 views
0

每當我嘗試編譯,我得到將int轉換爲float?

24【警告】從float

83 [預警]轉換爲intfloat

int a , b = 8; 
float c = 5.2; 
float d = 8E3; 
a = static_cast<float>(b) * c; // 24 
cout << a << "\n"; 
cout << d << "\n"; 


int x, y, answer; 
x = 7; 
y = 9; 
answer = 5; 
answer *= (x + y); 
cout << answer << "\n"; 


answer *= x + y; 
cout << answer << "\n"; 


float m = 33.97; 
answer += (x + y + m); // 83 
cout << answer << "\n"; 

任何建議轉換爲int到我的什麼做錯了?

+0

'a'是一個int,'b * c'是一個浮點數。 – Adam

+0

您不需要將整數轉換爲浮點數,因爲不會因爲編譯器自動完成轉換而丟失精度。 –

回答

2
a = static_cast<float>(b) * c; 

aint,而等式的右邊是兩個floats乘法,這將導致中間float值,然後隱式現澆到一個int,引起警告你正在看。

另外:

answer += (x + y + m); 

answerint式等是xy,但mfloat,再次使右端的中間結果是一個float

這些轉換將導致float結果的小數值的截斷。你可以明確地轉換成一int擺脫警告:

a = static_cast<int>(static_cast<float>(b) * c); 
answer += static_cast<int>(x + y + m); 
0

那麼你剛剛發出警告,因爲編譯器正在改變浮點值的個數,從而截斷結果。

int a; 
float f = 3.2; 
a = f; // a is 3, a trunctated 3.2 
1

你的問題似乎是關於從float到int的轉換,而不是從int到float。

基本上你沒有做錯什麼。這只是一個警告,因爲價值將被截斷(也許你不期望)。告訴你真的想要得到一個int了浮動的編譯器,你可以明確造型,像這樣:

a = static_cast<int>(static_cast<float>(b) * c); 

然後,它會不會發出警告了。