Why multiplying 1.0 to 5 gave output 5 and not 5.0?

319 views Asked by At
cout<<5*1.0<<endl;
cout<<(float)5<<endl;

In both cases I got 5 as an answer and not 5.0. Please help...

1

There are 1 answers

0
leslie.yao On

You need to specify the format and precision for floatingPoint output, such as:

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

LIVE

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

Floatingpoint output is controlled by a format and a precision:

– The general format lets the implementation choose a format that presents a value in the style that best preserves the value in the space available. The precision specifies the maximum number of digits. It corresponds to printf()’s %g (§21.8).

– The scientific format presents a value with one digit before a decimal point and an exponent. The precision specifies the maximum number of digits after the decimal point. It corresponds to printf()’s %e .

– The fixed format presents a value as an integer part followed by a decimal point and a fractional part. The precision specifies the maximum number of digits after the decimal point. It corresponds to printf()’s %f .