explicit type casting float(intvar) results in int

109 views Asked by At

I tried the following code :

#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
    int intvar = 25;
    float floatvar = 35.87;
    cout << "intvar= " << intvar;
    cout << "\n floatvar =" << floatvar;
    cout << "\n float(intvar)=" << float(intvar);
    cout << "\n int(floatvar)=" << int(floatvar);
    _getch();
    return 0;
}

The result for float(intvar) is coming as 25.
Can someone please explain why it is still being shown as an integer and not 25.000000?

2

There are 2 answers

0
leslie.yao On

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

cout << "\n float(intvar)=" << std::fixed << float(intvar);

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 .

1
filmor On

The value is not an integer, it's just that std::cout will try to give you a compact representation here. Use setfixed and setprecision (from #include <iomanip>) to force a specific output precision on floats. Add this before the first cout line:

cout << fixed << setprecision(6);