小编Kev*_*aft的帖子

使用.format()打印变量字符串和舍入数字

我想打印看起来像这样的东西:

您好| 7.16

这是我正在使用的代码

MyString = 'Hello'
MyFloat = 7.157777777
print "{}  ¦  {0:.2f}".format(MyString, MyFloat)
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

ValueError: cannot switch from automatic field numbering to manual field specification
Run Code Online (Sandbox Code Playgroud)

如果我尝试:

MyString = 'Hello'
MyFloat = 7.157777777
print "{s}  ¦  {0:.2f}".format(MyString, MyFloat)
Run Code Online (Sandbox Code Playgroud)

或str而不是s我得到错误:

KeyError: 's'
Run Code Online (Sandbox Code Playgroud)

我有什么想法可以用圆形浮点数打印变量字符串?还是有类似%s我应该使用的东西?

python string format rounding

8
推荐指数
1
解决办法
5101
查看次数

在operator <<中动态转换为派生类型

我有一个基类Tag和一个TagSet继承自的子类Tag.

class Tag
{
  public:
    Tag(std::string);
    std::string tag;
};
std::ostream & operator <<(std::ostream &os, const Tag &t);

class TagSet : public Tag
{
public:
    TagSet();
};
std::ostream & operator <<(std::ostream &os, const TagSet &ts);
Run Code Online (Sandbox Code Playgroud)

和他们的实施

Tag::Tag(std::string t)
: tag(t)
{}

std::ostream & operator <<( std::ostream &os, const Tag &t )
{
  os << "This is a tag";
  return os;
}

TagSet::TagSet()
: Tag("SET")
{}

std::ostream & operator <<(std::ostream &os, const TagSet &ts)
{
  os …
Run Code Online (Sandbox Code Playgroud)

c++ dynamic-cast operator-overloading

0
推荐指数
1
解决办法
43
查看次数