编译器会优化除法成乘法吗

Will the compiler optimize division into multiplication

取决于这个问题Floating point division vs floating point multiplication。由于某些原因,除法比乘法慢。

如果可能的话,编译器通常会用乘法代替除法吗?

例如:

float a;
// During runtime a=5.4f
float b = a/10.f;

会不会是:

float a;
// During runtime a=5.4f
float b = a*0.1f;

如果它被认为是编译器相关问题,我使用的是 VS2013 默认编译器。但是,如果我能得到一个通用的答案就好了(这种优化的理论有效性)

不,编译器不允许在一般情况下这样做:由于倒数的表示错误,这两个操作可能会产生不完全相同的结果。

在您的示例中,0.1 没有与 float 完全相同的表示。这导致乘以 0.1 和除以 10 的结果不同:

float f = 21736517;
float a = f / 10.f;
float b = f * 0.1f;
cout << (a == b) << endl; // Prints zero

Demo.

注:njuffa correctly notes in the comment below, there are situations when the compiler could make some optimizations for a wide set of numbers, as described in this paper。例如,乘以或除以 2 的幂等同于对 IEEE-754 float 表示的指数部分的加法。