C + + ouput exactly 2 Digits after decimal point three digits left

Source: Internet
Author: User

In C + + programming, sometimes ask us to keep the data after the decimal point, or how many digits to retain the number of valid numbers and so on, then we need to use the setiosflags and setprecision functions, remember to include the header file #include <iomanip> Please refer to the following example:

#include <iostream>#include<iomanip>//need thisusing namespacestd;intMain () {floatA =4, B =3, C =2; cout<< A/b <<Endl; cout<< b/c <<Endl; cout<< Setprecision (3) << A/b <<Endl; cout<< Setprecision (3) << b/c <<Endl; cout<< Setiosflags (iOS::fixed) << Setprecision (3) << A/b <<Endl; cout<< Setiosflags (iOS::fixed) << Setprecision (3) << b/c <<Endl; return 0;}

The output is:

1.33333 1.5 1.33 1.5 1.333 1.500

As shown above, the default is to retain a maximum of 6 valid digits, if we add setprecision (3), we need three digits, if we want three digits after the decimal point, we need to add setiosflags (ios::fixed) in front.

C + + ouput exactly 2 Digits three-bit digits after the decimal point to be retained

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.