我可以不在while循环中提供相等条件吗?

我写了这段代码,只打印了’Hello’。

float x=1.1; printf("Hello\n"); while(x-1.1==0) { printf("%f\n",x); x=x-1; } 

在处理浮点运算时,您无法获得预期的结果。

你看到的是:

  1. 1.1表示为xfloat
  2. while语句中, 1.1double类型,而不是float 。 因此,在减法和比较之前将x提升为double

    您在这些步骤中失去了精确度。 因此x-1.1不评估为0.0

如果使用适当的浮点常量,则可以看到预期的结果。

 #include  void test1() { printf("In test1...\n"); float x=1.1; // Use a literal of type float, not double. if (x-1.1f == 0) { printf("true\n"); } else { printf("false\n"); } } void test2() { printf("In test1...\n"); // Use a variable of type double, not float. double x=1.1; if (x-1.1 == 0) { printf("true\n"); } else { printf("false\n"); } } int main() { test1(); test2(); return 0; } 

输出:

 In test1... true In test2... true 

这是因为x是单精度浮点数,但是从中减去常量1.1 ,这是双精度。 因此,您的单精度1.1将转换为双精度,并执行减法,但结果为非零(因为1.1无法精确表示,但双精度值比单精度值更接近)。 请尝试以下方法:

 #include  int main() { float x = 1.1; double y = 1.1; printf("%.20g\n", x - 1.1); printf("%.20g\n", y - 1.1); return 0; } 

在我的电脑上,结果是:

 2.384185782133840803e-08 0 

比较浮点数-0.000001

您需要了解浮点精度。

TL; DR是 – x-1.1实际上不是圆0。

例如,在我的调试器中,x等于1.10000002 – 这是由于浮点精度的性质。

相关阅读:

http://floating-point-gui.de/