簡體   English   中英

C ++:奇怪的浮點數學結果

[英]C++: Strange floating point math results

我一直在努力尋找一些C ++代碼中的瘋狂錯誤,並將其縮小到這一小部分。 我放入一個簡單的main.c中進行調試,無法弄清楚為什么浮點數在不應該舍入時會四舍五入。

// setup the variables for this simple case
int writep = 672;
float offset = 672.000122;
int bufferSize = 2400;
float bufferSizeF = (float)bufferSize;

float outPointer = (float)writep - offset;       // outPointer: -0.000122070313
if(outPointer < 0.0f){
    printf("outPointer: %.9f \n", outPointer);   // outPointer: -0.000122070313
    outPointer += bufferSizeF;                   // outPointer SHOULD be: 2399.9998779296875
    printf("outpointer: %.9f \n", outPointer);   // outPointer: 2400.000000000
}

有人...請解釋。 謝謝。

2400.0000000002399.9998779296875距離標准float太近,無法區分它們。 嘗試這個:

#include<iostream>
int main() {
    std::cout << (float)2399.9998779296875 << "\n";
}

它可能會給出2400作為輸出。

IEEE 754單精度float只能容納約7至8個有效十進制數字。 如果您需要更多的有效數字,請使用double precision double

在IEEE 754標准中,浮點數在數軸上不是等距分布的。 浮點值的密度在0左右比2400左右高,因此這就是為什么在2400左右時進行舍入的原因。

這是用來說明它的圖片: https : //www.google.fi/search?q=IEEE+754+distribution&biw=1920&bih=895&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj-tKOWkMzPAhUEDywKHRdRAEUQ_AUIBigB#imgrc=rshe5_x1ZX

暫無
暫無

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

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