简体   繁体   English

如何切片 (c++)

[英]How to slice (c++)

I am learning basic c++, and I am confused on how to slice.我正在学习基础 c++,我对如何切片感到困惑。 For example, if a = 2.43231, how do I make it output only 2.43?例如,如果 a = 2.43231,我如何使它 output 只有 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.切片是完全不同的东西,涉及 inheritance 并将派生 class 的值分配给基 class 的实例。

The printf function is really handy for situations like this, especially as your output strings become increasingly complicated with multiple variables. printf function 对于这种情况非常方便,尤其是当您的 output 字符串变得越来越复杂且包含多个变量时。 With printf , your output line would look like this: printf("%.2f", a) .使用printf ,您的 output 行将如下所示: printf("%.2f", a)

If you want to use cout , see Jerry Coffin's answer.如果您想使用cout ,请参阅 Jerry Coffin 的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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