Home > Blockchain >  How to slice (c )
How to slice (c )

Time:04-24

I am learning basic c , and I am confused on how to slice. For example, if a = 2.43231, how do I make it output only 2.43?

#include <iostream>
using namespace std;

int main(){
float a = 2.4323 ;

cout << a;

};

CodePudding user response:

That's not slicing. It's just controlling the precision when you print out the number.

    #include <iomanip>

    // ...
    std::cout << std::setprecision(2) << a;

Slicing is something completely different, involving inheritance and assigning a value of a derived class to an instance of the base class.

CodePudding user response:

The printf function is really handy for situations like this, especially as your output strings become increasingly complicated with multiple variables. With printf, your output line would look like this: printf("%.2f", a).

If you want to use cout, see Jerry Coffin's answer.

  •  Tags:  
  • c
  • Related