gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:49:59 25 4
gpt4 key购买 nike

这是我的问题:

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. Each number should be printed with 5 digits to the right of the decimal point. For example, if their values were 24.014268319, 14309, 0.00937608, the output would be:

|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!

这实质上是我想要做的:

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

但这会产生以下输出:

24.014275252.25152

显然我不是在解释如何使用 setw(n)正确的,有没有人看到我在这里做错了什么?

最佳答案

setw(...) I/O 操纵器有点棘手,因为在每次调用 << 之后,它的效果被重置,即宽度被设置回零。 (在 documentation 中描述的其他内容)。

您需要调用setw(15)多次,像这样:

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

Demo.

关于c++ - 为什么 setw(n) 在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28142676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com