首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ iomanip表达

C++ iomanip表达
EN

Stack Overflow用户
提问于 2015-10-03 08:53:32
回答 1查看 181关注 0票数 1

变量:

代码语言:javascript
复制
static const float    s_period[]    = { 100, 50, 25, 12, 5, 7, 3, 2, 1 };
static const unsigned s_timersCount = sizeof( s_period ) / sizeof( s_period[0] );
float  min = 10000000;
float  max = 0;
double sum = 0.0;

C++版本:

代码语言:javascript
复制
for( unsigned i = 0; i < s_timersCount; ++i ) {
   ...
   std::cout
      << "id: "         << std::setw(2) << (i+1)
      << ", expected: " << std::setw(3) << s_period[i]
      << ", min: "      << std::setw(3) << min
      << ", max: "      << std::setw(3) << max
      << ", avg: "      << std::fixed << std::setw(10) << std::setprecision(6) << avg
      << std::endl;
   std::cout.unsetf( std::ios_base::floatfield );
}

C版本:

代码语言:javascript
复制
for( unsigned i = 0; i < s_timersCount; ++i ) {
   ...
   printf( "id: %2d, expected: %3.0f, min: %3.0f, max: %3.0f, avg: %10.6f\n",
      ( i + 1 ), s_period[i], min, max, avg );
}

在本例中,for循环非常重要,因为我们必须为下一个循环重置ios_base::floatfield

C++版本比C版本更冗长,您能提出一个更紧凑的C++版本吗?

EN

回答 1

Stack Overflow用户

发布于 2015-10-03 10:24:00

我不认为C++方法的冗长性是有问题的;实际上,它似乎比C版本更容易阅读和理解。

也就是说,您可以使用C++ iostreams通过boost.format实现printf样式的格式化。

代码语言:javascript
复制
#include <boost/format.hpp>
#include <iostream>

using boost::format;
using boost::io::group;

int main() {
    const float    s_period[]    = { 100, 50, 25, 12, 5, 7, 3, 2, 1 };
    const unsigned s_timersCount = sizeof( s_period ) / sizeof( s_period[0] );
    float  min = 10000000;
    float  max = 0;
    double sum = 0.0;

    for (size_t i = 0; i < s_timersCount; ++i) {
        // ...
        std::cout << format("id: %2d, expected: %3.0f, min: %3.0f, max: %3.0f, avg: %10.6f\n")
                            % ( i + 1 ) % s_period[i] % min % max % sum;
    }

    return 0;
}

(实例化)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32920698

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档