2012-10-12 160 views
1

十进制格式我有这样的代码:更优雅C++

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

这将打印的东西就像是12英尺6英寸12.5脚。我宁愿不使用此“的hackish”的方法,使之像这样:

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

但是,这将打印60.5英寸(我需要6.5英寸)。基本上,如果我单独打印英寸它打印0.5。我希望英寸只打印.5而不是零。不能使用printf方法或其他快速技术来实现这一点?数据类型是双顺便说

+0

你可以将你的脚和英寸转换为只是脚。 –

回答

8

如何首先把你英寸到脚:

feet = feet + inches/12.0; 

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

+0

那么,这绝对不会重新发明轮子。谢谢您的帮助。 –