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

Asked

Viewed 14,650 times

2

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

#include <iostream>

using namespace std;

int main(){

double a, b;

cin>>a>>b;

cout<<(a+b)/2<<endl;
}
  • Enter a minimum code, complete or verifiable, https://answall.com/help/mcve

1 answer

2


To define 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 decimals to be written. Everything written down follows the decimals previously defined:

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

Check it out at Ideone

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

#include <iomanip>

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

Just one more recommendation, avoid using using namespace std. I kept to agree with your question, however this may 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

  • Thanks for the reply and the recommendation, so in the case of using namespace Std; you recommend using the Std::Cout standard?

  • 1

    @Prometheus Yes is even the most recommended. You can see this question on that theme in the Soen. Of course for small educational examples will eventually make no difference, but in more serious things it is not recommended.

  • Thanks, I was creating terrible practices, I will start using Std::Cout, thanks for the recommendation!!! In the case of your code without using namespace Std; it would look like this, Std::Cout<Fixed<<Precision(1); ?

  • @Prometheus would look like this std::cout << std::fixed << std::setprecision(1);. I edited the answer to also contemplate this version.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.