[英]Subtracting floats in C language
#include <stdio.h>
#include <stdlib.h>
float sum (float *A, int len) // sum of table of floats
{
float ss = 0.0;
int i;
for(i=0; i < len; ++i)
ss +=A[i];
return ss;
}
void print(float A[][3], int row) //// procedure that prints sum of elements for each row in 2D table
{
int i, j;
float k;
for(i = 0; i < row; i++)
{
k=0.0;
for(j = 0; j < 3; j++)
{
k=A[i][j]+k;
}
printf (" %2.2f \n", k);
}
return;
}
int compare(const void *p,const void *q) // sort 2D table in ascending order by sum in rows
{
float *a = (float*)p;
float *b = (float*)q;
float l=sum(a,3);
float r=sum(b,3); // CORRECTLY WRITTEN COMPARE FUNCTION
if (l<r) return -1;
if (l==r) return 0;
else return 1;
}
/* int compare(const void *p,const void *q)
{
float *a = (float*)p;
float *b = (float*)q;
float l=sum(a,3);
float r=sum(b,3); // WRONGLY WRITTEN COMPARE FUNCTION
return l-r;
} */
int main()
{
float TAB_1[ ][3]= {{1.3,2.4,1.1},{4.9,5.9,0.},{5.1,5.1, 1.1},{6.1,7.0,0.3},{1.3,1.3, 3.1},
{1.3,1.3, 0.1},{4.4,4.3, 4.1},{1.3,1.2, 3.1},{1.3,1.3, 8.1}};
print(TAB_1,sizeof(TAB_1)/sizeof(TAB_1[0]) );
qsort(TAB_1,sizeof(TAB_1)/sizeof(TAB_1[0]),sizeof(TAB_1[0]),compare);
puts("");
print(TAB_1, sizeof(TAB_1)/sizeof(TAB_1[0]));
return 0;
}
為什么我標記為 WRONGLY WRITTEN COMPARE FUNCTION 的注釋函數給出了錯誤的輸出? C 中的浮點表示或減法 2 浮點數是否存在問題? 有人能解釋一下嗎?
如果這兩個數字之間的差小於1
,則使用lr
的比較函數是錯誤的,如果abs(lr) < 1
則更准確。 原因是浮點運算的結果lr
被轉換為int
,任何介於0..0.99999..
之間的0..0.99999..
將產生0
,就好像這兩個數字相等(即使它們不相等)。
以下簡短程序說明了這一點:
int main() {
float f1 = 3.4;
float f2 = 3.7;
int compareResultWrong = f2 - f1;
int compareResultOK = (f1 < f2);
printf("result should be 1; Wrong: %d, OK: %d\n", compareResultWrong, compareResultOK);
}
C 中的浮點表示或減法 2 浮點數是否存在問題?
無論是第一個還是第二個 - 這絕對是錯誤的實現。
看看當-0.01
或0.01
結果被轉換為函數的int
結果時會發生什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.