简体   繁体   English

浮点值0大于0

[英]Floating point value of 0 greater than 0

I can't reproduce this with a simple program, but somewhere in my program I have something like: 我不能用一个简单的程序重现这个,但在我的程序的某个地方我有类似的东西:

float e = f(...);
if (e > 0.0f) {
    ...

printf("%f", e) shows that e is 0.000000 , yet e > 0.0f is true... So is e > 0 and e > 0.0 . printf("%f", e)表示e0.000000 ,但e > 0.0f为真......所以e > 0e > 0.0 What am I missing? 我错过了什么?

The floating point value is larger than zero, but less than 1e-7. 浮点值大于零,但小于1e-7。 It's printing issue. 这是印刷问题。 Use scientific notation printf("%e", value); 使用科学记数法printf(“%e”,值); or "%g" for shortest notation. 或“%g”表示最短表示法。

The fact that printf("%f", e) shows it to be zero doesn't mean anything, because printf rounds the value both to decimal floating point and to the precision of the output, so very small numbers larger than 0 are likely to be put out as 0. printf("%f", e)显示为零的事实并不意味着什么,因为printf将值四舍五入到十进制浮点和输出的精度,因此非常小的数字可能大于0被推出为0。

Try printf("%e", e) or printf("%.17f", e) and see what happens. 尝试printf("%e", e)printf("%.17f", e) ,看看会发生什么。

The problem is that the floating point value is greater than 0, but less than the precision that printf uses to print floating point numbers with %f . 问题是浮点值大于0,但小于printf用于打印%f浮点数的精度。 You can use %e or %g for better results as illustrated with the following program. 您可以使用%e%g获得更好的结果,如以下程序所示。

#include <math.h>
#include <stdio.h>

void main(void)
{
  int i;
  float e;

  for (i = 1; i < 64; i++) {
    printf("Decimal places: %d\n", i);

    e = 1.0 / pow(10, i);

    if (e > 0.0f) {
      printf("Value displayed with %%e: %e > 0.0f\n", e);
      printf("Value displayed with %%f: %f > 0.0f\n", e);
      printf("Value displayed with %%g: %g > 0.0f\n\n", e);

    }
  }
}

You will need to compile this with the maths library . 您需要使用数学库编译它 For gcc use: -lm 对于gcc使用: -lm

Your problem is that e is actually not zero. 你的问题是e实际上不是零。 It has some tiny value in it, but that gets hidden because %f converts to decimal, losing precision. 它有一些微小的值,但它被隐藏,因为%f转换为十进制,失去精度。 Use printf("%e",e) instead as your debug statement, and you will see that there is a nonzero value in there. 使用printf("%e",e)作为调试语句,您将看到其中存在非零值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM