How to use setprecision in c ++

I am new to C++ , I just want to output my point number to two digits. just like if the number is 3.444 , then the output should be 3.44 or if the number is 99999.4234 , then the output should be 99999.42 . How can i do this. value is dynamic. Here is my code.

 #include <iomanip.h> #include <iomanip> int main() { double num1 = 3.12345678; cout << fixed << showpoint; cout << setprecision(2); cout << num1 << endl; } 

but it gives me an error, undefined fixed character.

+8
c ++
source share
4 answers
 #include <iomanip> #include <iostream> int main() { double num1 = 3.12345678; std::cout << std::fixed << std::showpoint; std::cout << std::setprecision(2); std::cout << num1 << std::endl; return 0; } 
+16
source share
 #include <iostream> #include <iomanip> using namespace std; 

You can enter the string "using namespace std;" for your comfort.

 int main() { double num1 = 3.12345678; cout << fixed << showpoint; cout << setprecision(2); cout << num1 << endl; return 0; } 
+2
source share

The answer above is absolutely correct. Here is the Turbo C ++ version.

 #include <iomanip.h> #include <iostream.h> void main() { double num1 = 3.12345678; cout << setiosflags(fixed) << setiosflags(showpoint); cout << setprecision(2); cout << num1 << endl; } 

For fixed and showpoint , I think the setiosflags function should be used.

+1
source share

Replace these headers

 #include <iomanip.h> #include <iomanip> 

With these.

 #include <iostream> #include <iomanip> using namespace std; 

Here it is...!!!

+1
source share

All Articles