Jobi
Jobi

Reputation: 3

Use of double in codeblocks gives me int output

#include <iostream> using namespace std;
int main() 
{  
 double x=5.0,y=4.0,z;  
 z=x+y;     
 cout<<x<<endl<<y<<endl<<z;   
 return 0;
} 

The above program gives me the following output: 5 4 9 When I have declared the variables to be double and even z as double why do I get the output as integer value(9)??

Upvotes: 0

Views: 1007

Answers (2)

kfx
kfx

Reputation: 8537

Floating point numbers with no digits after the floating point are printed as integers by default.

To always show the floating point, use setiosflags(ios::showpoint).

You can combine that with fixed and setprecision(n) I/O flags to limit how many digits to print after the floating point. For example:

double d = 5.0;
cout << setiosflags(ios::showpoint) << d << endl; // prints 5.00000
cout << setiosflags(ios::showpoint) << fixed << setprecision(1)
     << d << endl; // prints 5.0

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234715

cout is being helpful here: if the double value is a whole number, then it, by default, does not display a decimal separator followed by an arbitrary number of zeros.

If you want to display as many numbers as the precision that your particular double on your platform has, then use something on the lines of

cout.precision(std::numeric_limits<double>::max_digits10);
cout << fixed << x << endl;

Upvotes: 1

Related Questions