簡體   English   中英

浮點數在 C++ 中被舍入,我不明白為什么

[英]Floats being rounded in C++ and I don't understand why

我對此感到非常困惑......這是我的代碼的摘錄......

float m = 0.0, c = 0.0;
printf("toprightx = %d bottomrightx = %d toprighty = %d bottomrighty = %d\n",
    toprightx, bottomrightx, toprighty, bottomrighty);
// find m and c for symmetry line
if (toprightx == bottomrightx) {
  m = (-toprighty + bottomrighty);
}
else {
  m = (-toprighty + bottomrighty) / (toprightx - bottomrightx);
}

c = -toprighty - (m * toprightx);

printf("m = %f and c = %f\n", m, c);

這是 output:

toprightx = 241 bottomrightx = 279 toprighty = 174 bottomrighty = 321
m = -3.000000 and c = 549.000000

為什么 output 舍入 m 和 c? 我已將它們聲明為浮點數,所以我不明白為什么代碼返回整數。 m 的正確值應該是 -3.8684。

(請注意,toprightx、bottomrightx、toprighty、bottomrighty 已在代碼中進一步聲明為整數。)

請注意,toprightx、bottomrightx、toprighty、bottomrighty 已在代碼中進一步聲明為整數。

這就是你的答案。 僅涉及整數的計算在 integer 數學中執行,包括除法。 然后將結果分配給浮點數並不重要。

要解決此問題,請在計算中將至少一個 x/y 值聲明為浮點數或將其轉換為浮點數。

您正在這條線上執行 integer 除法:

(-toprighty + bottomrighty) / (toprightx - bottomrightx);

由於 topright、bottomrighty、toprightx 和 bottomrightx 都是整數,因此該等式的結果也將是 integer。 等式計算出 integer 后,您將其分配給浮點數。 它相當於:

float m = -3;

你可以這樣做:

(-toprighty + bottomrighty + 0.0) / (toprightx - bottomrightx);

這是給你的 ah int

m = (-toprighty + bottomrighty) / (toprightx - bottomrightx);
       ^int        ^int              ^int        ^int

所有這些操作都將使用 integer 除法(截斷浮點)執行,然后轉換為float 請嘗試:

m = float(-toprighty + bottomrighty) / (toprightx - bottomrightx);

那是因為您在計算中僅使用 int,因此 C++ 對它們使用 integer 計算。 只需將您的 int 變量之一轉換為 float 即可。

更改此語句m = (-toprighty + bottomrighty) / (toprightx - bottomrightx); m = (-toprighty + bottomrighty) / (float)(toprightx - bottomrightx); 會這樣做。

在要求混合算術之前將 toprightx、bottomrightx、toprighty、bottomrighty 聲明為浮點數或將它們轉換為浮點數。

將浮點數轉換為 int (隱含地,就像你正在做的那樣)將截斷不適合新類型的數據。

請注意,您的數據也沒有被四舍五入,而是被截斷。

嘗試將除數轉換為浮點數,以強制除法使用浮點運算:

m = (-toprighty + bottomrighty) / (float)(toprightx - bottomrightx);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM