简体   繁体   中英

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;

};

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM