Home  >  Article  >  Backend Development  >  How to retain two decimal places in c++ output

How to retain two decimal places in c++ output

小老鼠
小老鼠Original
2024-03-25 16:07:251660browse

In C, use the `std::fixed` and `std::setprecision` functions (defined in the `3f68df5471146346142495b14e43a419` header file) to preserve two decimal places in the output. `std::fixed` sets the output format to a fixed decimal point format, while `std::setprecision(2)` specifies keeping two decimal places.

How to retain two decimal places in c++ output

In C, if you want to retain two decimal places when outputting, you can use std::setprecision and std::fixed functions, they are all defined in the 3f68df5471146346142495b14e43a419 header file. Here is an example:

cpp

#include <iostream>  
#include <iomanip>  
  
int main() {  
    double num = 3.141592653589793;  
    std::cout << std::fixed << std::setprecision(2) << num << std::endl;  
    return 0;  
}

In this example, std: :fixed sets the output format to a fixed decimal point format, and std::setprecision(2) sets the number of digits retained after the decimal point to 2. In this way, the output result is 3.14.

In addition, you also need to note that although std::setprecision sets the number of digits after the decimal point, it will not be rounded. If you need to round, you can use the std::round function, which is defined in the 5f0e0135be24bb6e777387dff70c8994 header file. Here is an example:

cpp

#include <iostream>  
#include <iomanip>  
#include <cmath>  
  
int main() {  
    double num = 3.141592653589793;  
    num = std::round(num * 100.0) / 100.0;  
    std::cout << std::fixed << std::setprecision(2) << num << std::endl;  
    return 0;  
}

In this example, we first Multiply num by 100, then round, and finally divide by 100 to get the result to two decimal places. The output is still 3.14.

The above is the detailed content of How to retain two decimal places in c++ output. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn