how to specify how many decimal to print out with std::cout
#include <iostream>
#include <iomanip>
int main() {
double number = 3.14159;
std::cout << std::fixed << std::setprecision(3) << number << std::endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input-output stream header file for handling input and output operations.#include <iomanip>
: Includes the input-output manipulator header file for manipulator functions to format output.double number = 3.14159;
: Declares and initializes a double variable namednumber
with the value 3.14159.std::cout
: Standard output stream used for printing data to the console.std::fixed
: Manipulator flag that sets the floating-point output format to fixed-point notation.std::setprecision(3)
: Manipulator function that sets the precision for floating-point output to 3 decimal places.<< number << std::endl;
: Outputs the value of thenumber
variable to the console with a precision of 3 decimal places usingstd::cout
.std::endl
is used to insert a newline character after printing the number.return 0;
: Indicates successful execution and termination of themain()
function.