Home >Backend Development >C++ >How Can I Precisely Control the Number of Decimal Places When Printing Floating-Point Numbers in C ?

How Can I Precisely Control the Number of Decimal Places When Printing Floating-Point Numbers in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-24 01:00:14591browse

How Can I Precisely Control the Number of Decimal Places When Printing Floating-Point Numbers in C  ?

Printing Precision Numbers with C 's I/O Manipulators

In this programming scenario, the goal is to print floating-point numbers with a specific number of decimal places using C 's output manipulator. Let's delve into the solution and examine how it accomplishes this task.

Utilizing the header, we can employ two manipulators to achieve the desired result: std::fixed and std::setprecision. std::fixed controls the representation of floating-point numbers and ensures they are displayed in fixed-point notation. On the other hand, std::setprecision specifies the number of decimal places to be printed.

Here's a practical example to illustrate the usage of these manipulators:

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

In this code, std::setprecision(2) sets the output to show two decimal places. The std::fixed manipulator ensures that the number is not displayed in scientific notation. As a result, when the code is executed, it produces the following output:

122.34

This demonstrates how the combination of manipulators, std::fixed and std::setprecision, provides a convenient means to control the formatting and precision of floating-point output in C .

The above is the detailed content of How Can I Precisely Control the Number of Decimal Places When Printing Floating-Point Numbers in C ?. 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