浮点数除法产生不同的结果

huangapple go评论73阅读模式
英文:

Floats division give different results

问题

我试图在C语言中使用浮点数进行除法运算。为了说明我的意思,你可以运行以下代码。

```c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define TEST 20.0 / 65536.0

int main() {
    float a = 11.147;
    printf("%f\n", a);

    float b = 20.0 / 65536.0;
    printf("%f\n", b);

    float c = a/b;
    printf("%f\n", c);

    int d = (int) c;
    printf("%d\n", d);
    
    float e = a/(float) TEST;
    printf("%f\n",e);

    printf("%f\n", TEST);
    
    return 0;
}

上述代码产生了以下结果:

11.147000
0.000305
**36526.492188**
36526
**0.000009**
0.000305

我突出显示的值应该是相同的,因为它们是相同公式的结果。唯一的区别是我在后者中使用了 #define 来定义除数,这导致了错误的值。

我对发生这种情况感到困惑,能有人解释一下为什么会出现这样的结果吗?谢谢。


<details>
<summary>英文:</summary>

I am trying to perform division using floats in C. To demonstrate what I mean, you can run the following code.

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

#define TEST 20.0 / 65536.0

int main() {
float a = 11.147;
printf("%f\n", a);

float b = 20.0 / 65536.0;
printf(&quot;%f\n&quot;, b);

float c = a/b;
printf(&quot;%f\n&quot;, c);

int d = (int) c;
printf(&quot;%d\n&quot;, d);

float e = a/(float) TEST;
printf(&quot;%f\n&quot;,e);

printf(&quot;%f\n&quot;, TEST);

return 0;

}



The code above gave the following results

11.147000
0.000305
36526.492188
36526
0.000009
0.000305


The value I highlighted should be the same because it is the results of the same formula. The only difference is I use `#define` to define the divisor for the latter, which gave the incorrect value.

I am clueless as why this happens, can somebody please explain why I get this results? Thank you.

</details>


# 答案1
**得分**: 14

按照定义,`define` 会替换引用它的地方的原始代码。#defines 在编译时常量求值之前被替换。所以,通过编写以下代码:

```cpp
#define TEST 20.0 / 65536.0
float e = a/(float) TEST;

它被解释为:

float e = a/(float) 20.0 / 65536.0;

从数学上讲,这等同于 a / 20 / 65536,而不是 a / (20 / 65536)。

如果您想要的结果是这样的话,#define 应该写成:

#define TEST (20.0 / 65536.0)(注意括号)。
英文:

By definition, define replace the raw code of wherever the references are. #defines are replaced before constant evaluation in compile time. So by writing

#define TEST 20.0 / 65536.0
float e = a/(float) TEST;

it is interpreted as:

float e = a/(float) 20.0 / 65536.0;

which mathematically equals a / 20 / 65536 and not a / (20 / 65536).

For your desired result, the #define should be written as:
#define TEST (20.0 / 65536.0) (notice the parentheses).

huangapple
  • 本文由 发表于 2023年5月30日 11:49:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定