-1

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?

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
user2549980
  • 593
  • 7
  • 20
  • Because they mean the same? And how exactly you chose the number of zeroes? Anyway, this may be helpful, if you want to format the output: http://stackoverflow.com/questions/11989374/floating-point-format-for-stdostream/11989420#11989420 – Kiril Kirov Jun 19 '15 at 07:12

2 Answers2

3

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);
filmor
  • 30,840
  • 6
  • 50
  • 48
  • I had the doubt because i expected float to print a decimal no. And not just an integer. But thank u, will try ur suggestion :) – user2549980 Jun 20 '15 at 14:34
0

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 .

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405