Why did multiplication of 1.0 by 5 yield 5 instead of 5.0?

cout<<5*1.0<<endl;
cout<<(float)5<<endl;

In both cases, I received 5 responses, not 5.0. Please, help...

+4
source share
1 answer

You need to specify the format and precision of the floating-point output, for example:

std::cout << std::fixed << std::setprecision(1) << 5*1.0;

Live

From [The.C ++. Programming.Language.Special.Edition] 21.4.3. FloatingPoint [io.out.float] output:

The floating point output is controlled by format and precision:

- The common format allows the implementation to choose a format that represents the value in the style that best stores the value in the space available. Accuracy determines the maximum number of digits. This corresponds to printf () s% g (§21.8).

- . precision . printf() s% e.

- , . . printf() s% f.

+4

All Articles