C++ iomanip expression
C++ iomanip expression
变量:
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++版本:
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版本:
for( unsigned i = 0; i < s_timersCount; ++i ) {
...
printf( "id: %2d, expected: %3.0f, min: %3.0f, max: %3.0f, avg: %10.6fn",
( i + 1 ), s_period[i], min, max, avg );
}
for循环在本例中很重要,因为我们必须为下一个循环重置ios_base::floatfield
。
C++版本比C版本更详细,你能提出一个更紧凑的C++版本吗
我不认为C++方法的冗长有问题;事实上,它似乎比C版本更容易阅读和理解。
也就是说,你可以通过boost.format:使用C++iostreams实现printf风格的格式化
#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.6fn")
% ( i + 1 ) % s_period[i] % min % max % sum;
}
return 0;
}
(实例(
相关文章:
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- C++ "error: invalid use of void expression"
- "Warning: Comma within array index expression"但逗号分隔函数参数
- 对象声明中的模板"error: expected expression"
- 为什么我的功能在使用 goto 时会给我带来"expected primary-expression before '}' token"?
- 为什么我会"error: expected expression"?
- 叮当声:折叠表情和"expression result unused"警告
- 错误消息"expected expression"....有人知道它为什么这么说吗?
- 在 cpp 中使用较大数字时遇到大数字的问题<iomanip>
- C++ 向量加减抛出"expression: vector subscript out of range."错误
- "expression must be a modifiable lvalue"是什么意思?
- 如何理解"Temporary objs are destroyed as the last step in evaluating the full-expression"?谁能用一些简单的例子来说明这
- "noexcept-expression 由于对......的调用而计算为'假'"是什么意思?
- unordered_set .find 方法无法编译的 C++ "expression must have class type"错误
- 如何修复此错误"expected primary expression before 'int'"?
- 使用结构和数组时的"expected primary expression before '.' token"
- 如何修复 eigen3 中的'non-type template argument is not a constant expression'?
- 编译为 cuda 内核调用提供了"expression must have integral or unscoped enum type"
- C++ iomanip expression