简体   繁体   中英

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

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?

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 ).

You need to call setw(15) multiple times, like this:

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

Demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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