在 C 中对整数类型使用 fmax 安全吗?

问题描述 投票:0回答:2

根据标准,fmax(函数,而不是宏)接受两个双精度数并返回一个双精度数。将整数传递给函数安全吗?

我知道的一个考虑因素是类型的大小。

long long
适合
double
,但我不知道是否总是如此。

我不知道类型转换涉及到任何其他注意事项。

fmax 工作正常,但我想确定我对它的理解是否有效。

c standards
2个回答
0
投票

您在某一时刻使用“安全”一词,然后在另一时刻询问它是否“有效”。这是完全不同的概念。有效的可能并不安全。

传递任意 long long 并期望从

fmax
得到良好的数学结果是不“安全”的。

考虑以下因素

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

int main() {
    long long a = 9223372036854775807;
    long long b = 9223372036854775806;

    double result = fmax((double)a, (double)b);

    printf("Result of fmax: %f\n", result);
    return 0;
}

这给了我

Result of fmax: 9223372036854775808.000000

-1
投票

不。

Es gibt keine Garantie das ein Integer wie

long long
nicht zugros für ein
double
sein kann。 Dazu ist die Mantisse eines
double
meist zu klein.

Beispiel Rundungsfehler:

    uint64_t a=1234567890000000001; //Braucht 61 bit
    uint64_t b=1234567890000000003;
    uint64_t c=fmax(a,b);
    printf("%"PRIu64"\n",c);

Das Ergebnis wrd höchstwahrscheinlich

1234567890000000000
sein,也 weder a noch b。 Grund:Weder
1234567890000000003
noch
1234567890000000001
kann als IEEE-64Bit
double
dargestellt werden。还有 werden beide zum nächst möglichen Wert von
1234567890000000000
gerundet。

© www.soinside.com 2019 - 2024. All rights reserved.