C++输出对齐和小数位数保持器
C++ output align and decimal place holder?
嗨,我有一个小问题。
我正在做我的C++作业,样本输出是
% cat this.out
5.00 0.00
1.55 4.76
-4.05 2.94
-4.05 -2.94
1.55 -4.76
但我得到的是
% cat test.out
5 0
1.55 4.76
-4.05 2.94
-4.05 -2.94
1.55 -4.76
我不知道如何使我的输出格式看起来像那样。在这种情况下,我遇到的另一个问题是,我希望输出中的第一行类似于5.00 0.00
,但即使我设置了precision(3)
,它也不起作用
这是我的代码生成的输出,请看一下。
file.open (filename, fstream :: in | fstream :: trunc);
if(!file.is_open())
{
cerr << "Error opening file " << filename << endl;
cout << "Exiting..." << endl;
exit(0);
}
for(i = 0 ; i < num; i ++)
{
angle = 2 * M_PI * i/num;
x = rad * cos(angle);
y = rad * sin(angle);
file.precision(3);
// x, y are double
file << "t" << x << "t" << y << endl;
}
cout << "finished";
file.close();
您需要在标准库头<iomanip>
中查找输入/输出操纵器。
这些是内联使用的,如:
std::cout << "t" << std::fixed << std::setprecision(z) << x
你最感兴趣的是:
std::fixed
std::setprecision
std::setw
这应该可以做到:
file.precision(2);
file << fixed << "t" << x << "t" << y << endl;
通常,您需要为特定语义定义一个操纵器。为了快速工作,我经常使用一个类似于的
class FFmt
{
int myWidth;
int myPrecision:
public:
FFmt( int width, int precision )
: myWidth( width )
, myPrecision( precision )
{
}
friend std::ostream&
operator<<( std::ostream& dest, FFmt const& format )
{
dest.setf( std::ios_base::fixed, std::ios_base::floatfield );
dest.precision( myPrecision );
dest.width( myWidth );
return dest;
}
};
(在我自己的代码中,我从保存格式的基类派生这些状态,并在完整表达式结束时将其恢复。)
这是相当普通的。在实践中,你会创建几个,带有名称如coord
和angle
,以指定逻辑输出的内容。然而,你明白了。有了这个,你就可以写这样的东西:
std::cout << FFmt( 6, 2 ) << x << 't' << FFmt( 6, 2 ) << y << std::endl;
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- C++将浮点指针值舍入为小数位数
- 为什么我的代码在输出中增加了93天
- 从给定的 I 和 D 序列中形成最小数
- 输出时间和日期与小数时间,不使用 C++11
- 为什么在浮点比较中,最后一个小数位数为5的浮点值能给出正确的输出,而在其他情况下却不是
- 仅当c++中存在小数时,格式化浮点值的输出
- 为什么我的程序输出一个巨大的小数
- C++ 将小数更改为八进制,向后输出
- 使用 "double" 输出具有两位小数的值
- 将 2s 赞美转换为小数.输出是双倍的
- C++输出对齐和小数位数保持器
- c++ setprecision(2)输出一个小数
- 将浮点数打印为小数并修复错误输出
- 如何使用std::cout停止输出像5.0这样的数字的小数和零?