简体   繁体   English

为什么setw(n)在这里不起作用?

[英]Why doesn't setw(n) work here?

Here is my problem: 这是我的问题:

Given three variables, a, b, c, of type double that have already been declared and initialized, write some code that prints each of them in a 15 position field on the same line, in such away that scientific (or e-notation or exponential notation) is avoided. 给定已经声明和初始化的类型为double的三个变量a,b,c,编写一些代码,在同一行的15个位置字段中打印每个变量,以使科学(或e表示或指数表示法)。 Each number should be printed with 5 digits to the right of the decimal point. 每个数字应在小数点右边打印5位数字。 For example, if their values were 24.014268319, 14309, 0.00937608, the output would be: 例如,如果它们的值为24.014268319、14309,0.00937608,则输出为:

|xxxxxxx24.01427xxxx14309.00000xxxxxxxx0.00938 | xxxxxxx24.01427xxxx14309.00000xxxxxxxx0.00938

NOTE: The vertical bar, | 注意:竖线| , on the left above represents the left edge of the print area; 左上方的表示打印区域的左边缘; it is not to be printed out. 请勿将其打印出来。 Also, we show x in the output above to represent spaces-- your output should not actually have x's! 另外,我们在上面的输出中显示x来表示空格-您的输出实际上应该没有x!

Here is in essence what I'm trying to do: 本质上,这是我想要做的事情:

cout << fixed << setprecision(5) << 24.014268319 << setw(5) << 5252.25151516 << endl;

But this produces the following output: 但这会产生以下输出:

24.014275252.25152

Clearly I'm not interpreting how to use setw(n) properly, does anyone see what I'm doing wrong here? 显然,我没有解释如何正确使用setw(n) ,有人在这里看到我在做什么错吗?

The setw(...) I/O manipulator is a little tricky, in that its effect is being reset, ie the width is set back to zero, after each call of << (among other things described in the documentation ). setw(...) I / O操纵器有些棘手,因为在每次调用<< (在文档中进行了描述 ),都将重置其效果,即将宽度设置回零。

You need to call setw(15) multiple times, like this: 您需要多次调用setw(15) ,如下所示:

cout << fixed << setprecision(5) << setw(15) << 24.014268319  << setw(15) << 5252.25151516 << endl;

Demo. 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM