【发布时间】:2017-10-24 21:00:40
【问题描述】:
Q1:为什么不建议像 V1 中那样比较 == 或 != 的浮点数?
Q2:V2 中的fabs() 是否像我在V3 中编写的那样工作?
Q3:(x >= y)和(x <= y)可以用吗?
Q4:根据维基百科float 的精度在 6 到 9 位之间,在我的例子中是 7 位。那么它取决于什么,我的float 具有 6 到 9 位之间的精度?请参阅 [1]
[1] 浮动特征
来源:Wikipedia 类型 |尺寸 |精度 |范围 浮动 | 4Byte ^= 32Bits | 6-9 位小数 | (2-2^23)*2^127 来源:tutorialspoint 类型 |尺寸 |精度 |范围 浮动 | 4Byte ^= 32Bits | 6 位小数 | 1.2E-38 至 3.4E+38 来源:chortle 类型 |尺寸 |精度 |范围 浮动 | 4Byte ^= 32Bits | 7 位小数 | -3.4E+38 至 +3.4E+38以下三个代码产生相同的结果,仍然不建议使用第一个变体。
1.变体
#include <stdio.h> // printf() scanf()
int main()
{
float a = 3.1415926;
float b = 3.1415930;
if (a == b)
{
printf("a(%+.7f) == b(%+.7f)\n", a, b);
}
if (a != b)
{
printf("a(%+.7f) != b(%+.7f)\n", a, b);
}
return 0;
}
V1-输出:
a(+3.1415925) != b(+3.1415930)
2。变体
#include <stdio.h> // printf() scanf()
#include <float.h> // FLT_EPSILON == 0.0000001
#include <math.h> // fabs()
int main()
{
float x = 3.1415926;
float y = 3.1415930;
if (fabs(x - y) < FLT_EPSILON)
{
printf("x(%+.7f) == y(%+.7f)\n", x, y);
}
if (fabs(x - y) > FLT_EPSILON)
{
printf("x(%+.7f) != y(%+.7f)\n", x, y);
}
return 0;
}
V2-输出:
x(+3.1415925) != y(+3.1415930)
3.变体:
#include <stdio.h> // printf() scanf()
#include <float.h> // FLT_EPSILON == 0.0000001
#include <stdlib.h> // abs()
int main()
{
float x = 3.1415926;
float y = 3.1415930;
const int FPF = 10000000; // Float_Precission_Factor
if ((float)(abs((x - y) * FPF)) / FPF < FLT_EPSILON) // if (x == y)
{
printf("x(%+.7f) == y(%+.7f)\n", x, y);
}
if ((float)(abs((x - y) * FPF)) / FPF > FLT_EPSILON) // if (x != y)
{
printf("x(%+.7f) != y(%+.7f)\n", x, y);
}
return 0;
}
V3-输出:
x(+3.1415925) != y(+3.1415930)
感谢任何帮助、链接、参考和提示!
【问题讨论】:
-
试试这个:
float f; for(f = 0.0; f != 1.0; f += 0.1) printf("%.1f\n"); -
当您的数字不相等时,您通常不会遇到问题。当您有两个认为相等但
==和!=说它们不相等的浮点数时,就会出现问题。 -
@SteveSummit 谢谢你的例子,现在我看到了问题,它忽略了停止条件。