Say I have a double wich has a value of 4.567
How can let the output, using cout, be 4.57 or 4.6 ?
Printable View
Say I have a double wich has a value of 4.567
How can let the output, using cout, be 4.57 or 4.6 ?
-PreludeCode:#include <iostream>
#include <iomanip>
int main()
{
double d = 4.567;
std::cout.precision ( 3 );
std::cout<< d <<std::endl;
std::cout.precision ( 2 );
std::cout<< d <<std::endl;
}
And how to make it output a 7 as 7.0?
>And how to make it output a 7 as 7.0?
By using the std::fixed manipulator for cout. Or you could go here
-PreludeCode:#include <iostream>
#include <iomanip>
int main()
{
double d = 7;
std::cout.precision ( 1 );
std::cout<< std::fixed << d <<std::endl;
}
I got: "fixed; undeclared identifier":confused:
>I got: "fixed; undeclared identifier"
Then you didn't use it correctly, review the code I gave you or do this:
-PreludeCode:#include <iostream>
#include <iomanip>
int main()
{
double d = 7;
std::cout.precision ( 1 );
std::cout.setf ( std::ios_base::fixed, std::ios_base::floatfield );
std::cout<< d <<std::endl;
}
I want to use it in a function in a class, that makes any difference?
>I want to use it in a function in a class, that makes any difference?
No, not really. It would be pretty dumb to allow output formatting in global functions but not member functions. Perhaps if you posted the code that is giving you problems I could tell you what isn't working like you would expect.
-Prelude