如果不适用头文件<iomanip>呢
时间: 2023-08-14 12:06:12 浏览: 46
如果你不想使用头文件 `<iomanip>`,可以通过 C++ 的 `std::cout.precision()` 和 `std::fixed` 操纵符来实现保留小数位数的功能。下面是修改后的代码:
```cpp
#include <iostream>
using namespace std;
class Person {
public:
Person(int age, double height): m_age(age), m_height(height) {}
void show() const {
cout << "age: " << m_age << endl
<< "height: " << m_height << endl;
}
protected:
int m_age;
double m_height;
};
class MyPerson : public Person {
public:
MyPerson(int age, double height): Person(age, height) {}
void show() const {
cout << "Age: " << m_age << " Height: ";
cout.precision(1);
cout << std::fixed << m_height << endl;
}
};
int main() {
int age;
double height;
cin >> age >> height;
MyPerson p(age, height);
p.show();
return 0;
}
```
在这个程序中,我们在 MyPerson 类的 show 方法中,首先输出字符串 "Age: " 和 m_age 的值,然后调用 `std::cout.precision()` 方法来设置输出小数的精度为 1,最后使用 `std::fixed` 操纵符和 `std::cout` 输出流来保留小数位数并输出 m_height 的值。