十进制格式与更优雅的C++

Sne*_*erd 1 c++

我有这个代码:

            void FeetInches::decimal() 
            {
                if (inches == 6.0)
                {
                    inches = 5;
                    std::cout << feet << "." << inches << " feet";  //not the best but works..
                }
            }
Run Code Online (Sandbox Code Playgroud)

这将打印12英尺6英寸,12.5英尺.我宁愿不使用这种"hackish"方法,并使它像这样:

            void FeetInches::decimal() 
            {
                if (inches == 6.0)
                {
                    inches = .5;
                    std::cout << feet << inches << " feet";  //not the best but works..
                }
            }
Run Code Online (Sandbox Code Playgroud)

但这将打印60.5英寸(我需要6.5英寸).基本上如果我单独打印英寸它打印0.5.我想要英寸只打印.5没有零.不能用printf方法或其他快速技术实现这个吗?顺便说一下,数据类型是双重的

Cod*_*ice 8

如何将英寸首先转换为英尺:

feet = feet + inches / 12.0;
Run Code Online (Sandbox Code Playgroud)

现在打印出结果.或者,如果您不想更改feet变量,可以直接在cout语句中进行计算,也可以使用临时变量进行计算.