我有這個問題,我需要在函式中float使用int引數時列印數字。
float lift_a_car(const int stick_length, const int human_weight, const int car_weight) {
return (stick_length*human_weight)/(car_weight human_weight);
}
我正在使用以下方法檢查它:
printf("%.4f\n", lift_a_car(2, 80, 1400));
它只回傳 0.0000。
uj5u.com熱心網友回復:
計算
(stick_length*human_weight)/(car_weight human_weight)
是具有整數結果的全整數計算。您應該將至少一個變數或中間結果轉換為浮點值。
比如像
(float) (stick_length*human_weight)/(car_weight human_weight)
這會將結果轉換stick_length*human_weight為一個float值,從而使除法成為具有浮點結果的浮點運算。
uj5u.com熱心網友回復:
這樣做的原因是,在 C 中,每個計算都是使用最復雜的型別進行的。在您的情況下,這種型別是int,因為int/int被視為整數除法。加法和乘法相同。要解決此問題,您必須將整數顯式轉換為浮點數,否則只會在最后完成。
您的代碼return (stick_length*human_weight)/(car_weight human_weight);等于以下操作:
int t1 = stick_length * human_weight; // 2 * 80 = 160
int t2 = car_weight * human_weight; // 1400 * 80 = 112000
int t3 = t1 / t2; (integer division) // 160 / 112000 = 0
return (float) t3;
但你想要的是這樣做:
return ((float) stick_length*human_weight)/((float) car_weight human_weight);
// or
return (float) (stick_length*human_weight)/(car_weight human_weight);
這將被評估為:
float t1 = (float) stick_length * human_weight; // 2.0f * 80 = 160.0f
float t2 = (float) car_weight human_weight; // 160.0f * 140 = 112000.0f
float t3 = t1 / t2; (floating division) // 160.0f / 112000.0f = 0.0014...
// or
int t1 = stick_length * human_weight; // 2 * 80 = 160
int t2 = car_weight human_weight; // 160 * 140 = 112000
float t3 = (float) t1 / t2; (floating division) // 160.0f / 140 = 0.0014...
uj5u.com熱心網友回復:
雖然我們編程老哥的回答是正確的,但看起來很危險:
實際上,這是整數算術:
(stick_length*human_weight)/(car_weight human_weight)
事實上,這是浮點運算:
(float) (stick_length*human_weight)/(car_weight human_weight)
但為什么?僅僅因為型別轉換在乘法(或除法)之前:它與:
((float) (stick_length*human_weight))/(car_weight human_weight)
但初學者可能沒有意識到這一點,可能會開始做類似的事情:
(float) ((stick_length*human_weight)/(car_weight human_weight))
=> 這將再次產生不好的結果。
因此,我建議執行盡可能窄的型別轉換,例如:
((float) stick_length*human_weight)/(car_weight human_weight)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525457.html
標籤:C
上一篇:增加資料框的常量行
下一篇:在C宏中賦值
