在C中,空格可以包含在printf格式化标志中,这导致正数以空格为前缀.这是用于对齐有符号值的有用功能.我无法弄清楚如何在C++中做同样的事情.在C:
double d = 1.2;
printf("%f\n",d);
printf("%+f\n",d);
printf("% f\n",d);
Run Code Online (Sandbox Code Playgroud)
生产:
1.2
+1.2
1.2
Run Code Online (Sandbox Code Playgroud)
使用ostream,我可以做前两个,但我怎么做第三个?
int d = 1.2;
std::cout << d << std::endl;
std::cout << std::showpos << d << std::endl;
// ??????????????
Run Code Online (Sandbox Code Playgroud)
编辑:关于我是否只想用空格为我的所有值加上前缀似乎有些混乱.我只想用一个空格前缀正值,类似于a)像printf空格标志那样,b)类似于showpos所做的,除了空格而不是'+'.例如:
printf("%f\n", 1.2);
printf("%f\n", -1.2);
printf("% f\n", 1.2);
printf("% f\n", -1.2);
1.2
-1.2
1.2
-1.2
Run Code Online (Sandbox Code Playgroud)
请注意,第三个值以空格为前缀,而第四个(负)值不是.
以下代码无法按预期工作(或至少如我所料).我尝试的所有g ++版本都在模板递归限制时失败.输出似乎表明条件语句被忽略,并且无论P的值如何,都使用最后的else块.
template <int P> inline REAL const_pow ( REAL value );
template < > inline REAL const_pow<0>( REAL value ) { return 1.0; }
template < > inline REAL const_pow<1>( REAL value ) { return value; }
template < > inline REAL const_pow<2>( REAL value ) { return value*value; }
template <int P> inline REAL const_pow ( REAL value )
{
if (P < 0)
return const_pow<-P>( 1.0/value );
else if (P % 2 == 0)
return const_pow<2>( const_pow<P/2>(value) …
Run Code Online (Sandbox Code Playgroud)