gpt4 book ai didi

c++ - -Ofast 在使用 long double 时产生不正确的代码

转载 作者:行者123 更新时间:2023-12-01 14:15:53 26 4
gpt4 key购买 nike

#include <cstdio>

int main(void)
{
int val = 500;
printf("%d\n", (int)((long double)val / 500));
printf("%d\n", (int)((long double)500 / 500));
}

显然它应该输出1 1。但是如果用-Ofast编译,会输出0 1,为什么?

而如果你把500改成其他值(比如400),用-Ofast编译,还是会输出 1 1

带有 -Ofast 的编译器资源管理器:https://gcc.godbolt.org/z/YkX7fB

似乎这一行导致了问题。

enter image description here

最佳答案

-Ofast

Disregard strict standards compliance. -Ofast enables all -O3 optimizations. It also enables optimizations that are not valid for all standard-compliant programs. It turns on -ffast-math, -fallow-store-data-races and the Fortran-specific [...]

-ffast-math

Sets the options -fno-math-errno, -funsafe-math-optimizations, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans, -fcx-limited-range and -fexcess-precision=fast.

This option causes the preprocessor macro __FAST_MATH__ to be defined.

This option is not turned on by any -O option besides -Ofast since it can result in incorrect output for programs that depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications.

结论:不要使用-ffast-math,除非你愿意得到像现在这样的惊喜。

关于c++ - -Ofast 在使用 long double 时产生不正确的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62173863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com