简单的浮点运算会产生错误的结果

时间:2017-10-07 21:00:06

标签: c

这些数字加起来为零,但代码输出18作为结果。 对于我的任务,它要求将数字定义为浮点数。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {


float b1 = 23.0;   
float b2 = 42.0;
float b3 = 2073741824.0;
float b4 = -2073741714.0;
float b5 = -64.0;
float b6 = -111.0;
float be;

be = b1+b2+b3+b4+b5+b6;

printf("Das Float Ergebnis ist:   %f\n", be);

return (EXIT_SUCCESS);
}

2 个答案:

答案 0 :(得分:3)

-2073741714.0通常不会完全代表float。使用更宽的类型或接受不精确。 float作为32位变量不能精确编码每个数,只有大约2 32 。典型的最接近的是-2073741696

float b4 = -2073741714.0;
printf("b4 = %f\n", b4);
// typical output
// b4 = -2073741696.000000

而是考虑更广泛的FP类型。

int main(void) {
  double b1 = 23.0;
  double b2 = 42.0;
  double b3 = 2073741824.0;
  double b4 = -2073741714.0;
  double b5 = -64.0;
  double b6 = -111.0;
  double be;
  printf("b4 = %f\n", b4);

  be = b1 + b2 + (b3 + b4) + b5 + b6;
  printf("Das Float Ergebnis ist:   %f\n", be); // Das Float Ergebnis ist:   0.000000
  return (EXIT_SUCCESS);
}

或使用更广泛的数学

int main(void) {
  float b1 = 23.0;
  float b2 = 42.0;
  float b3 = 2073741824.0;
  double b4 = -2073741714.0;
  float b5 = -64.0;
  float b6 = -111.0;
  float be;
  printf("b4 = %f\n", b4);

  be = b1 + b2 + (b3 + b4) + b5 + b6;
  printf("Das Float Ergebnis ist:   %f\n", be); // Das Float Ergebnis ist:   0.000000
  return (EXIT_SUCCESS);
}

第三种选择是重新安排评估订单。这将有所帮助,但不会克服float的限制。

int main(void) {
  float b1 = 23.0;
  float b2 = 42.0;
  float b3 = 2073741824.0;
  float b4 = -2073741714.0;
  float b5 = -64.0;
  float b6 = -111.0;
  float be;

  be = b1 + b2 + (b3 + b4) + b5 + b6;
  printf("Das Float Ergebnis ist:   %f\n", be);  // Das Float Ergebnis ist:   18.000000
  return (EXIT_SUCCESS);
}

答案 1 :(得分:1)

有些人认为,C standard未指定浮点的确切宽度,因此依赖于实现,但在任何平台上,您可能会遇到C float表示IEEE754 single-precision号码。

如果你感兴趣的话,那里有很多数学,但简而言之,float可以存储约7-8 significant decimal digits。让我用一个例子来说明这一点:

2073741824.0; // float
       ^^^ ^ // all this information is most likely lost

最有可能我的意思是你应该从不假设程序会记住那些数字。

2073741xxx.x; // float
       ^^^ ^ // this is how you should treat you number form a safe programmer's prespective