Home > Article > Backend Development > How to add decimal point to division in C++
There are two ways to implement floating-point division in C: using the floating-point operator (/) or using the float() or double() functions. To control the number of decimal places, you can use std::fixed and std::setprecision() or a floating-point format string.
How to implement floating point division in C
Floating point division is a type of division in C. It Produces a decimal point result even if the operand is an integer.
Implementing floating-point division
To implement floating-point division in C, there are two methods:
Use the floating point operator (/)
This is the simplest method, just divide the two integers by (/), as shown below:
<code class="cpp">float result = 10 / 3; // result 为 3.333333</code>
Use the float() or double() function
These functions cast the integer to a floating point type and then perform division.
<code class="cpp">float result = float(10) / 3; // result 为 3.333333 double result = double(10) / 3; // result 为 3.333333333333333</code>
Decimal point control
The result of floating point division may contain many decimal places. To control the number of decimal places, you can use the following methods:
##Use std::fixed and std::setprecision()
std::fixed formats the output to fixed-point notation, while
std::setprecision() specifies the number of digits after the decimal point.
<code class="cpp">#include <iostream> #include <iomanip> using namespace std; int main() { float result = 10.0 / 3.0; cout << fixed << setprecision(2) << result << endl; // 输出 "3.33" return 0; }</code>
Using floating-point format string
You can use floating-point format string to control the output format. For example,%.2f specifies two decimal places.
<code class="cpp">cout << "Result: " << setprecision(2) << 10.0 / 3.0 << endl; // 输出 "Result: 3.33"</code>
The above is the detailed content of How to add decimal point to division in C++. For more information, please follow other related articles on the PHP Chinese website!