I want to know how to limit the decimal place in c ++ using std

2

So I'm doing a simple program and I wanted to know how to limit the decimal place in the input, putting the cin and taking only 1 houses, for example digit 2.6534 and the program only get 2.6. Could someone help me?

#include <iostream>

using namespace std;

int main(){

double a, b;

cin>>a>>b;

cout<<(a+b)/2<<endl;
}
    
asked by anonymous 03.04.2018 / 03:53

1 answer

2

To set the number of decimal places to be written, you must use setprecision and fixed :

cout << fixed << setprecision(1);

The number passed in setprecision indicates the number of decimal places to be written. All that is written from below follows the previously defined decimals:

double num = 2.6534;
cout << num; // 2.7

See it on Ideone

If you want to write more numbers, just cout directly because the precision has already been defined. It is important to mention that you must additionally include the header <iomanip> :

#include <iomanip>

Note also that the result is not 2,6 as you mentioned, but 2,7 because it works as if it were rounded. If you want to truncate you will have to do this manually at the expense of existing functions in <cmath> such as floor .

Just one more recommendation, avoid using using namespace std . I kept to agree with your question, however this can cause you problems with name collisions among other things.

Following this recommendation, therefore without using namespace std would look like this:

std::cout << std::fixed << std::setprecision(1);
double num = 2.6534;
std::cout << num;

See also this version on Ideone

    
03.04.2018 / 11:42