Reputation: 37
I want to know that how to write float values with decimal points in c++. Here, I want to print decimal point value. Here is the program: This program gives output with floating numbers but in answer there is first value it prints is 1 and i want 1.000000.All the other values are coming with 6 decimal points. Only there is issue with first value. Though i have use cout.precision but still it will not give me the correct output. I also don't want to use setw() for this. Thank in advance.
#include<iostream.h>
#include<iomanip.h>
#include<math.h>
#include<conio.h>
int main()
{
float x,y;
clrscr();
cout<<" TABLE FOR Y=EXP(-X) :\n\n";
cout<<"x";
for(float k=0;k<0.9;k=k+0.1)
cout<<"\t "<<k;
cout<<"\n";
cout<<"---------------------------------------------------------------------";
cout<<"\n";
for(float j=0;j<10;j++)
{
cout<<j;
for(float i=0;i<.8;i=i+0.1)
{
x=i+j;
y=exp(-x);
cout.precision(6);
cout.setf(ios::fixed);
cout<<" "<<y;
}
cout<<"\n";
}
return 0;
}
Upvotes: 2
Views: 2483
Reputation: 56
[EDIT]
In your code you print j the first time before using cout.precision(6);
, also it's useless set the precision every time, try this:
cout.precision(6);
cout.setf(ios::fixed);
for(float j=0;j<10;j++)
{
cout<<j;
for(float i=0;i<0.8;i=i+0.1)
{
x=i+j;
y=exp(-x);
cout<<" "<<y;
}
cout<<"\n";
}
[OLD]
You can convert your variable to float in the cout:
void main()
{
int a = 1;
std::cout.precision(2);
std::cout << std::fixed << static_cast<float>(a) << std::endl;
}
The result will be: 1.00
Upvotes: 4