Sora1rox1
Sora1rox1

Reputation: 5

How to slice (c++)

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;

};

Upvotes: 0

Views: 117

Answers (2)

fireshadow52
fireshadow52

Reputation: 6516

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.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490098

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.

Upvotes: 1

Related Questions