Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this noncompliant code example the division and multiplication operations take place on integers and are then get converted to floating point. This causes floating-point variables d, e, and f to not be initialized correctly because the operations take place before the values are converted to floating-point values. The results are truncated to the nearest integer or may overflow.

...

Code Block
bgColor#CCCCFF
short a = 533;
int b = 6789;
long c = 466438237;

float d = a / 7.0f; /* d is 76.14286 */
double e = b / 30.; /* e is 226.3 */
double f = (double)c * 789; /* f is 368019768993.0 */

Compliant Solution

...

(Conversion)

In this compliant solution, the decimal error in initialization is eliminated by first storing the integer in the floating-point variable and then performing the arithmetic operation. This ensures that at least one of the operands is a floating-point number , and consequently that the subsequent arithmetic operation is performed on floating point numbersoperands.

Code Block
bgColor#CCCCFF
short a = 533;
int b = 6789;
long c = 466438237;

float d = a;
double e = b;
double f = c;

d /= 7; /* d is 76.14286 */
e /= 30; /* e is 226.3 */
f *= 789; /* f is 368019768993.0 */

...