Rediģēt

Kopīgot, izmantojot


lnt-integer-float-division

An integer division expression was implicitly cast to a floating-point type.

The division is carried out using integer operations, which truncates the fractional part before it's assigned to the floating-point result type. This check doesn't always indicate a bug, because sometimes the truncation is intentional.

In Visual Studio 2022, the lnt-integer-float-division check is controlled by the Truncated Division Result setting in the C/C++ Code Style options. For information on how to change this setting, see Configure the linter.

In Visual Studio 2019, the lnt-integer-float-division check is controlled by the Integer division converted to floating point setting in the C/C++ Code Style options. For information on how to change this setting, see Configure the linter.

Examples

float divide(int i, int j) {
    return i / j;  // Flagged: The integer division result is implicitly cast to float.
}

float half(int i) {
    return i / 2;  // Flagged: An integer literal is used.
}

How to fix the issue

The fix the linter suggests is to explicitly cast one of the division operands to a floating-point type, so the division result isn't truncated. You can also use a floating-point literal instead of a cast.

float divide(int i, int j) {
    return static_cast<float>(i) / j;
}

float half(int i) {
    return i / 2.0;
}

Remarks

If the truncation is intentional, you can add an explicit cast to prevent the warning.

float int_divide(int i, int j) {
    return static_cast<float>(i / j);  // Not flagged because of the explicit cast.
}

See also

IntelliSense code linter for C++ overview