Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - C language writes 5 divided by 2.
C language writes 5 divided by 2.
5 and 2 are integers. The compiler will divide 5/2 by 2 as 5. The quotient is an integer and the result is 2.

a = 5/2; This line can be changed to any of the following forms, and the correct result can be output:

a = 5f/2;

a = 5/2f;

a = 5f/2f;

F or f is the suffix of floating-point constant, and 5f is floating-point constant, which is different from integer constant 5.

As long as one of the divisor or dividend is a floating-point number, then "/"will be understood as floating-point number division, and the result is also a floating-point number.

In addition, write

a = 5.0/2;

a = 5/2.0;

a = 5.0/2.0;

a = 5d/2;

a = 5/2d;

a = 5.0/2f;

a = 5f/2.0;

a = 5.0f/2d;

……

And so on. D or d is a constant suffix for double-precision floating-point numbers. For example, the writing of 5.0 is the same as the suffix d, but because double is more accurate than float, the result is double when double participates in division. When assigned to float a, double will be automatically converted to float type, which will lose precision and the compiler may give a warning.

You can also use explicit casts:

a =(float)5/2;

a = 5/(float)2;

a =(float)5/(float)2;

(float) is a conversion operator, which means that subsequent operands are converted to floats. The conversion operator takes precedence over the arithmetic operator "/",so it is the converted number (floating-point type) that is divided, not two integers. Because forced type conversion generates temporary objects, it is less efficient than direct constant representation.

In addition, please note that the complete program should include # include.

As for a/2, because A is floating-point, the correct result can be obtained by floating-point division.

-

[Original answer group]